# app_script_history

id: 60cb6f8c99321b9efaa468b2
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.17 23:55:56.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}
 

/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

 

/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


id: 60cddf755db21ecdc234d5bb
scriptid: 60c8556748741fc1098abc3c
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.19 20:29:44.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{

  toastr.info("1");
}


id: 60cddf755db21ecdc234d5c1
scriptid: 60c8556748741fc1098abc3c
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.19 20:29:58.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{

  toastr.info("2");
}


id: 60d056760c74933b9218f161
scriptid: 60a31c3c5db27838e0c0129e
tablename: app_script
clientip: 192.168.1.140
username: sa
createdate: 2021.06.21 17:11:48.000
script:
function getImageList1()
{
    return getImageList("凭证");
}
function getImageList2()
{
    return getImageList("附件");
}


//@comment (group=,caption=得到待归档的图片清单,needRightControl=true)
function getImageList(groupName) {
     
    //排除掉回收站的图片
    var sql= "select * from  dzpz_pzfj  where  gguid='" + currentGUID() + "'  and groupname='"+groupName+"'  order by info1 ";
    println( sql);
    var ds = newDataStore("pz", sql); // info1 是客户端文件创建的时间，以它排序
    var n = ds.retrieve();
   
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return  { success:true,  data:ret};

}


function  downloadPackage()
{
    return createArchive("dzpz", currentGUID() , false);
}


id: 60d056760c74933b9218f16a
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.21 17:12:34.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret= downloadPackage();
    if( ret.success)
    {
        alert( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d056760c74933b9218f173
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.21 17:24:39.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret= downloadPackage();
    if( ret.success)
    {
        $.alert( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d056760c74933b9218f179
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.21 17:24:55.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret= downloadPackage();
    console.dir(ret);
    if( ret.success)
    {
        $.alert( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d056760c74933b9218f17f
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.21 17:26:53.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret= downloadPackage();
    console.dir(ret);
    if( ret.success)
    {
        openWindow( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d087860c749ebb228557a5
scriptid: 60d0840b0c749ebb22855746
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 20:41:40.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    id= p.id;

    //重排序
    var ds=newDataStore("pz" , "select id , ")

    return createArchive("dzpz", id , false);


}


id: 60d087860c749ebb228557b3
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 20:42:51.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID()}));
    console.dir(ret);
    if( ret.success)
    {
        openWindow( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d087860c749ebb228557b9
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 20:43:37.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID(), 
    overwrite:true  //如果已存在，则重新生成
    }));
    console.dir(ret);
    if( ret.success)
    {
        openWindow( ret.url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d08cc30c7456c5a0d37bf7
scriptid: 60d0840b0c749ebb22855746
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 21:04:27.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    var id= p.id;
    var overwrite= p.overwrite; 

    //重排序
    var ds=newDataStore("pz" , "select id , ")

    return createArchive("dzpz", id , overwrite);


}


id: 60d08cc30c7456c5a0d37bff
scriptid: 60d0840b0c749ebb22855746
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 21:04:41.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    var id= p.id;
    var overwrite= p.overwrite; 

    
    return createArchive("dzpz", id , overwrite);


}


id: 60d08cc30c7456c5a0d37c05
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 21:15:32.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    packageGo('download');
}


function cb_view_onClick()
{
    packageGo('view');
}

function packageGO( action)
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID(), 
    overwrite:true  //如果已存在，则重新生成
    }));
    console.dir(ret);
    if( ret.success)
    {
        let url= ret.url;
        if( action=='download')  url= url.replace('action=view' , 'action=download');
        openWindow(  url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d08cc30c7456c5a0d37c0b
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 21:22:24.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    packageGo('download');
}


function cb_view_onClick()
{
    packageGo('view');
}

function packageGo( action)
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID(), 
    overwrite:true  //如果已存在，则重新生成
    }));
    console.dir(ret);
    if( ret.success)
    {
        let url= ret.url;
        if( action=='download')  url= url.replace('action=view' , 'action=download');
        openWindow(  url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d0a2b8993254220bd859b1
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:47:06.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'work';
    var tableName = 'maintenance_list_detail';
    //ret.message="select id,userid,verifiername from maintenance_list where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from maintenance_list where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL('work', "delete from maintenance_list_detail where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "客户名称": "wldw_name",
        "店铺账号": "store_loginname",
        "登录账号": "loginname",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}

//导入旺旺维护记录；
function backend_import_workorder(gguid) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }
    var ds1 = newDataStore("work", "select op_userid,year(mdate) as nian,month(mdate) as yue from maintenance_list where gguid='" + gguid + "'");
    ds1.setOnceRetrieveCount(1);
    ds1.retrieve();
    if (ds1.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var op_userid = ds1.getString(0, "op_userid");
    var nian = ds1.getString(0, "nian");
    var yue = ds1.getString(0, "yue");
    var sql = "select a.wldw_id " +
        "   ,b.name as wldw_name " +
        "   ,c.store_loginname " +
        "   ,a.addtime,a.endtime " +
        "   ,a.days_m" + yue + " as days " +
        " from dbo.f_get_wwwh_list(" + nian + ") a " +
        "  left join v_customer b on a.wldw_id=b.id " +
        "  left join v_store c on a.wldw_id=c.wldw_id " +
        " where a.days_m" + yue + ">0 and a.userid=" + op_userid +
        " order by b.name asc "
    //ret.message=sql;
    //return ret;
    var ds2 = newDataStore('oa', sql);
    ds2.retrieve('');

    runSQL('work', "update maintenance_list_detail set status=0,starttime=null,endtime=null,days=null where gguid='" + gguid + "'"); //数据结果重置
    // runSQL('work', "delete maintenance_list_detail where gguid='" + gguid + "' and ifnull(wldw_name,'')='' "); //自动删除客户名称为空的数据
    // return ret;
    var ds = newDataStore('work', "select * from maintenance_list_detail where wldw_name<>'' and gguid='" + gguid + "' order by wldw_name asc");
    ds.setUpdateProperty("maintenance_list_detail", "id", "*", "id");
    ds.retrieve('');
    var rowCount = ds.getRowCount();
    var row = -1
    var date2 = date2yyyymmdd(nextDate(thisMonthLastDay(nian, yue), 1));
    var userid = currentUserId();
    for (var i = 0; i < ds2.getRowCount(); i++) {
        row = ds.find('store_loginname=="' + ds2.getString(i, 'store_loginname') + '" ', 0, rowCount - 1);
        if (row >= 0) {
            //客户名称存在
            //若客户名称不一致备注填入导入的客户名称
            if (ds.getString(row, "wldw_name") != ds2.getString(i, "wldw_name")) {
                ds.setValue(row, "bz", ds.getString(row, "wldw_name"));
            }

            //填入客户资料及判定结果
            ds.setValue(row, "wldw_id", ds2.getString(i, "wldw_id")); //客户ID
            ds.setValue(row, "wldw_name", ds2.getString(i, "wldw_name")); //客户ID
            //ds.setValue(row, "store_loginname", ds2.getString(i, "store_loginname"));
            ds.setValue(row, "starttime", ds2.getString(i, "addtime")); //划入时间
            if (ds2.getString(i, "endtime") >= date2) {
                ds.setValue(row, "endtime", ds2.getString(i, "endtime")); //服务结束时间
            }
            ds.setValue(row, "days", ds2.getString(i, "days")); //本月服务天数
            if (ds.getInt(row, 'days') >= 15) {
                ds.setValue(row, "status", 1); //本月服务天数大于等于15天，判定业绩有效
            } else {
                ds.setValue(row, "status", 0); //本月服务天数大于等于15天，判定业绩无效
            }

        } else {
            continue; // 如果不存在， 暂时不再插入记录； 如下代码不再执行

            //客户不存在，则插入一条记录
            row = ds.insertRow(99999);
            ds.setValue(row, "id", newGuid());
            ds.setValue(row, "gguid", gguid);
            ds.setValue(row, "lastmodifieddate", newDate());
            ds.setValue(row, "userid", userid);
            ds.setValue(row, "username", '系统');

            //填入客户资料及判定结果
            ds.setValue(row, "wldw_id", ds2.getString(i, "wldw_id")); //客户ID
            ds.setValue(row, "wldw_name", ds2.getString(i, "wldw_name")); //客户ID
            ds.setValue(row, "store_loginname", ds2.getString(i, "store_loginname"));
            ds.setValue(row, "starttime", ds2.getString(i, "addtime")); //划入时间
            if (ds2.getString(i, "endtime") >= date2) {
                ds.setValue(row, "endtime", ds2.getString(i, "endtime")); //服务结束时间
            }
            ds.setValue(row, "days", ds2.getString(i, "days")); //本月服务天数
            if (ds.getInt(row, 'days') > 15) {
                ds.setValue(row, "status", 1); //本月服务天数大于等于15天，判定业绩有效
            } else {
                ds.setValue(row, "status", 0); //本月服务天数大于等于15天，判定业绩无效
            }
        }
    }
    println("ds2_rowCount:" + toString(ds2.getRowCount()));
    println("ds_rowCount:" + toString(ds.getRowCount()));
    if (ds.update(true)) {
        ret.success = true
    } else {
        ret.message = ds.error.message;
    }
    return ret;
}

//做单
function zuodan(gguid, mDate) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }

    var achievement_ds = newDataStore("work", "select op_userid,mDate,jobtype_code from achievement where gguid='" + gguid + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    if (achievement_ds.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var achievement_detail_ds = newDataStore("work", "select * from achievement_detail where DATE_FORMAT(mDate,'%Y-%m') = '" + mDate + "' and order_type = 1");
    achievement_detail_ds.setUpdateProperty("achievement_detail", "id", "*", "id");
    var row = achievement_detail_ds.retrieve();
    if (row > 0) {
        ret.message = "该月份已有数据，不允许插入";
        return ret;
    }
    var yy_single_detailed_tmp_ds = newDataStore("sixi_oa_pg", "select * from achievement.yy_single_detailed_tmp_history where bill_lading_type = '1' and report_time  = '" + mDate + "' and settle_status = 1 and bill_lading_type = '1'");
    var row2 = yy_single_detailed_tmp_ds.retrieve();
    var contract_ds = newDataStore("sixi_oa", "select id,nid,clid,numbers,htmoney,startime,endtime from contract ");
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    var uid_ds = newDataStore("sixi_oa", "select uid from money");
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    // var news_ds = newDataStore("sixi_oa","select IslogInAliWang from news");
    println("++++:" + row2)
    for (var i = 0; i < row2; i++) {
        var contract_billno = yy_single_detailed_tmp_ds.getString(i, "number");
        var row = achievement_detail_ds.insertRow(0);
        achievement_detail_ds.setValue(0, "id", newGuid());
        achievement_detail_ds.setValue(0, "gguid", gguid);
        achievement_detail_ds.setValue(0, "contract_billno", contract_billno);//合同编号
        achievement_detail_ds.setValue(0, "mdate", mDate + "-01");//业绩月份
        achievement_detail_ds.setValue(0, "wldw_name", yy_single_detailed_tmp_ds.getValue(i, "enterprisen_name"));//客户名称
        achievement_detail_ds.setValue(0, "store_loginname", yy_single_detailed_tmp_ds.getValue(i, "aliAccount"));//店铺账号
        contract_ds.setOnceRetrieveCount(1);
        contract_ds.retrieve("numbers = '" + contract_billno + "'");
        achievement_detail_ds.setValue(0, "wldw_id", contract_ds.getValue(0, "nid"));//客户id
        achievement_detail_ds.setValue(0, "contract_amount", contract_ds.getValue(0, "htmoney"));//合同金额
        achievement_detail_ds.setValue(0, "contract_starttime", yy_single_detailed_tmp_ds.getValue(i, "start_time"));//合同开始时间
        achievement_detail_ds.setValue(0, "contract_endtime", yy_single_detailed_tmp_ds.getValue(i, "end_time"));//合同结束时间
        htlx2_ds.setOnceRetrieveCount(1);
        htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
        achievement_detail_ds.setValue(0, "htlx2", htlx2_ds.getValue(0, "code"));//合同类型id
        achievement_detail_ds.setValue(0, "htlx2_name", htlx2_ds.getValue(0, "name"));//合同类型名称
        achievement_detail_ds.setValue(0, "htlx", htlx2_ds.getValue(0, "htlx"));//业务类型
        money_ds.setOnceRetrieveCount(1);
        money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        achievement_detail_ds.setValue(0, "payment_amount", money_ds.getValue(0, "amount"));//到款金额
        uid_ds.setOnceRetrieveCount(1);
        uid_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        manage_ds.setOnceRetrieveCount(1);
        manage_ds.retrieve("id = " + yy_single_detailed_tmp_ds.getValue(i, "user_id") + "");
        achievement_detail_ds.setValue(0, "op_userid", manage_ds.getValue(0, "sixiId"));//运营人员ID
        achievement_detail_ds.setValue(0, "op_username", manage_ds.getValue(0, "realname"));//运营人员
        achievement_detail_ds.setValue(0, "op_departmentid", manage_ds.getValue(0, "class2"));//运营部门
        achievement_detail_ds.setValue(0, "order_type", "1");//业务类型
        achievement_detail_ds.setValue(0, "status", 1);//status
        achievement_detail_ds.setValue(0, "tidan_id", yy_single_detailed_tmp_ds.getValue(i, "task_id"));//提单id
        TaskLadingCn_ds.setOnceRetrieveCount(1);
        TaskLadingCn_ds.retrieve("id = '" + yy_single_detailed_tmp_ds.getValue(i, "task_id") + "'");
        // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
        // if (is_wangwang > 0) {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        // }
        var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
        if (is_wangwang == 1) {
            achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        }
        else if (is_wangwang == 2) {
            achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        }
        achievement_detail_ds.setValue(0, "achievement_amount", 0);//业绩金额
        achievement_detail_ds.setValue(0, "is_zdyy", TaskLadingCn_ds.getValue(0, "isSetYY") || 0);//是否指定运营
        achievement_detail_ds.setValue(0, "job_code", achievement_ds.getValue(0, "job_code"));//作业项目
        achievement_detail_ds.setValue(0, "jobrole_code", achievement_ds.getValue(0, "jobrole_code"));//作业角色
        achievement_detail_ds.setValue(0, "jobtype_code", achievement_ds.getValue(0, "jobtype_code"));//绩效项目
        achievement_detail_ds.setValue(0, "contract_id", contract_ds.getValue(0, "id"));//合同id
        achievement_detail_ds.setValue(0, "is_add", 0);//是否手动添加
        achievement_detail_ds.setValue(0, "is_xiugai", 0);//是否修改
    }
    if (achievement_detail_ds.update(true)) {
        ret.success = true;
        ret.message = "拉取成功";

    } else {
        ret.message = achievement_detail_ds.getError().getMessage();
    }
    return ret;
}

//续费单
function xufei(gguid, mDate) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }
    var achievement_ds = newDataStore("work", "select * from achievement where gguid='" + gguid + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    if (achievement_ds.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var achievement_detail_ds = newDataStore("work", "select * from achievement_detail where DATE_FORMAT(mDate,'%Y-%m') = '" + mDate + "' and order_type = 2");
    achievement_detail_ds.setUpdateProperty("achievement_detail", "id", "*", "id");
    var row = achievement_detail_ds.retrieve();
    if (row > 0) {
        ret.message = "该月份已有数据，不允许插入";
        return ret;
    }
    var yy_renew_details_list_ds = newDataStore("sixi_oa_pg", "select * from achievement.yy_renew_details_list_history where report_time  = '" + mDate + "'and settle_status = 1");
    var row2 = yy_renew_details_list_ds.retrieve();
    var contract_ds = newDataStore("sixi_oa", "select id,nid,clid,numbers,htmoney,startime,endtime,case when ISNULL(OldUpgradeId, 0)!=0 then OldUpgradeId when ISNULL(oldXfId, 0)!=0 then oldXfId else 0 end as previous_contract_id from contract ");
    var contract2_ds = newDataStore("sixi_oa", "select clid from contract where id = '" + contract_ds.getValue(0, "previous_contract_id") + "'");
    var htclass_ds = newDataStore("sixi_oa", "select xfType from htclass");
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    var uid_ds = newDataStore("sixi_oa", "select uid from money");
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    var aliuser_ds = newDataStore("sixi_oa", "SELECT username FROM aliuser");
    println("++++:" + row2)
    for (var i = 0; i < row2; i++) {
        var contract_billno = yy_renew_details_list_ds.getString(i, "numbers");
        var row = achievement_detail_ds.insertRow(0);
        achievement_detail_ds.setValue(0, "id", newGuid());
        achievement_detail_ds.setValue(0, "gguid", gguid);
        achievement_detail_ds.setValue(0, "contract_billno", contract_billno);//合同编号
        achievement_detail_ds.setValue(0, "mdate", mDate + "-01");//业绩月份
        achievement_detail_ds.setValue(0, "wldw_name", yy_renew_details_list_ds.getValue(i, "company_name"));//客户名称
        contract_ds.setOnceRetrieveCount(1);
        contract_ds.retrieve("numbers = '" + contract_billno + "'");
        achievement_detail_ds.setValue(0, "wldw_id", contract_ds.getValue(0, "nid"));//客户id
        achievement_detail_ds.setValue(0, "contract_amount", contract_ds.getValue(0, "htmoney"));//合同金额
        achievement_detail_ds.setValue(0, "contract_starttime", yy_renew_details_list_ds.getValue(i, "contract_start_time"));//合同开始时间
        achievement_detail_ds.setValue(0, "contract_endtime", yy_renew_details_list_ds.getValue(i, "contract_end_time"));//合同结束时间
        aliuser_ds.setOnceRetrieveCount(1);
        aliuser_ds.retrieve("nid = '" + contract_ds.getValue(0, "nid") + "'");
        achievement_detail_ds.setValue(0, "store_loginname", aliuser_ds.getValue(0, "username"));//店铺账号
        htlx2_ds.setOnceRetrieveCount(1);
        htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
        achievement_detail_ds.setValue(0, "htlx2", htlx2_ds.getValue(0, "id"));//合同类型id
        achievement_detail_ds.setValue(0, "htlx2_name", htlx2_ds.getValue(0, "name"));//合同类型名称
        achievement_detail_ds.setValue(0, "htlx", htlx2_ds.getValue(0, "htlx"));//业务类型
        money_ds.setOnceRetrieveCount(1);
        money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        achievement_detail_ds.setValue(0, "payment_amount", money_ds.getValue(0, "amount"));//到款金额
        uid_ds.setOnceRetrieveCount(1);
        uid_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        manage_ds.setOnceRetrieveCount(1);
        manage_ds.retrieve("id = " + yy_renew_details_list_ds.getValue(i, "user_id") + "");
        achievement_detail_ds.setValue(0, "op_userid", manage_ds.getValue(0, "sixiId"));//运营人员ID
        achievement_detail_ds.setValue(0, "op_username", manage_ds.getValue(0, "realname"));//运营人员
        achievement_detail_ds.setValue(0, "op_departmentid", manage_ds.getValue(0, "class2"));//运营部门
        contract2_ds.setOnceRetrieveCount(1);
        contract2_ds.retrieve();
        htclass_ds.setOnceRetrieveCount(1);
        htclass_ds.retrieve("id = '" + contract2_ds.getValue(0, "clid") + "'");
        // if (htclass_ds.getValue(0, "xfType") == 1) {
        achievement_detail_ds.setValue(0, "order_type", "2");//业务类型(是中阿，续费)
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "order_type", "7");//业务类型（不是中阿，转代运营停服）
        // }
        achievement_detail_ds.setValue(0, "status", 1);//status
        achievement_detail_ds.setValue(0, "tidan_id", yy_renew_details_list_ds.getValue(i, "task_id"));//提单id
        TaskLadingCn_ds.setOnceRetrieveCount(1);
        TaskLadingCn_ds.retrieve("htID = '" + yy_renew_details_list_ds.getValue(i, "contract_id") + "'");
        // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
        var achievement_amount = getNumberFromSQL2("sixi_oa", "  select case WHEN xfType in  (1,4,2,3) THEN money when contract_nature=0 and admin = 48 or xfType not in (1,2,3,4,5,6)  then 0  when admin in (52,2)or xfType not in (1,2,3,4,5,6) then 0 else money end as money from (select m.*,ma.admin,c.contract_nature,h.xfType from (select sum(Money) as money,max(uid) as uid,max(hid) as hid from money where hid = '" + contract_ds.getValue(0, "id") + "' ) m left join manage ma on ma.id = m.uid LEFT JOIN (select id,clid,case when ISNULL(OldUpgradeId, 0)!=0 then 2 when ISNULL(oldXfId, 0)!=0 then 1 else 0 end as contract_nature from contract ) c on c.id = m.hid  left join htclass h on h.id = c.clid)a ");
        // if (is_wangwang > 0) {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        // }
        var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
        if (is_wangwang == 1) {
            achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        }
        else if (is_wangwang == 2) {
            achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        }
        achievement_detail_ds.setValue(0, "achievement_amount", achievement_amount);//业绩金额
        achievement_detail_ds.setValue(0, "is_zdyy", TaskLadingCn_ds.getValue(0, "isSetYY") || 0);//是否指定运营
        achievement_detail_ds.setValue(0, "job_code", achievement_ds.getValue(0, "job_code"));//作业项目
        achievement_detail_ds.setValue(0, "jobrole_code", achievement_ds.getValue(0, "jobrole_code"));//作业角色
        achievement_detail_ds.setValue(0, "jobtype_code", achievement_ds.getValue(0, "jobtype_code"));//绩效项目
        achievement_detail_ds.setValue(0, "contract_id", yy_renew_details_list_ds.getValue(i, "contract_id"));//合同id
        achievement_detail_ds.setValue(0, "previous_contract_endtime", yy_renew_details_list_ds.getValue(i, "contract_old_end_time"));//上一份合同结束时间
        achievement_detail_ds.setValue(0, "is_add", 0);//是否手动添加
        achievement_detail_ds.setValue(0, "is_xiugai", 0);//是否修改
    }

    if (achievement_detail_ds.update(true)) {
        ret.success = true;
        ret.message = "拉取成功";

    } else {
        ret.message = achievement_detail_ds.getError().getMessage();
    }
    return ret;
}


//加帐号
function addzhanghao(gguid, mDate) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }
    var achievement_ds = newDataStore("work", "select * from achievement where gguid='" + gguid + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    if (achievement_ds.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var achievement_detail_ds = newDataStore("work", "select * from achievement_detail where DATE_FORMAT(mDate,'%Y-%m') = '" + mDate + "' and order_type = 5");
    achievement_detail_ds.setUpdateProperty("achievement_detail", "id", "*", "id");
    var row = achievement_detail_ds.retrieve();
    if (row > 0) {
        ret.message = "该月份已有数据，不允许插入";
        return ret;
    }
    var yy_add_account_introduce_list_ds = newDataStore("sixi_oa_pg", "select * from achievement.yy_add_account_introduce_list_history where report_type = 1 and report_time  = '" + mDate + "'and settle_status = 1");
    var row2 = yy_add_account_introduce_list_ds.retrieve();
    var contract_ds = newDataStore("sixi_oa", "select id,nid,clid,numbers,htmoney,startime,endtime from contract ");
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    var uid_ds = newDataStore("sixi_oa", "select uid from money");
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    var aliuser_ds = newDataStore("sixi_oa", "SELECT username FROM aliuser");
    println("++++:" + row2)
    for (var i = 0; i < row2; i++) {
        var contract_billno = yy_add_account_introduce_list_ds.getString(i, "numbers");
        var row = achievement_detail_ds.insertRow(0);
        achievement_detail_ds.setValue(0, "id", newGuid());
        achievement_detail_ds.setValue(0, "gguid", gguid);
        achievement_detail_ds.setValue(0, "contract_billno", contract_billno);//合同编号
        achievement_detail_ds.setValue(0, "mdate", mDate + "-01");//业绩月份
        achievement_detail_ds.setValue(0, "wldw_name", yy_add_account_introduce_list_ds.getValue(i, "company_name"));//客户名称
        contract_ds.setOnceRetrieveCount(1);
        contract_ds.retrieve("numbers = '" + contract_billno + "'");
        achievement_detail_ds.setValue(0, "wldw_id", contract_ds.getValue(0, "nid"));//客户id
        achievement_detail_ds.setValue(0, "contract_amount", contract_ds.getValue(0, "htmoney"));//合同金额
        achievement_detail_ds.setValue(0, "contract_starttime", yy_add_account_introduce_list_ds.getValue(i, "contract_start_time"));//合同开始时间
        achievement_detail_ds.setValue(0, "contract_endtime", yy_add_account_introduce_list_ds.getValue(i, "contract_end_time"));//合同结束时间
        aliuser_ds.setOnceRetrieveCount(1);
        aliuser_ds.retrieve("nid = '" + contract_ds.getValue(0, "nid") + "'");
        achievement_detail_ds.setValue(0, "store_loginname", aliuser_ds.getValue(0, "username"));//店铺账号
        htlx2_ds.setOnceRetrieveCount(1);
        htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
        achievement_detail_ds.setValue(0, "htlx2", htlx2_ds.getValue(0, "code"));//合同类型id
        achievement_detail_ds.setValue(0, "htlx2_name", htlx2_ds.getValue(0, "name"));//合同类型名称
        achievement_detail_ds.setValue(0, "htlx", htlx2_ds.getValue(0, "htlx"));//业务类型
        money_ds.setOnceRetrieveCount(1);
        money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        achievement_detail_ds.setValue(0, "payment_amount", money_ds.getValue(0, "amount"));//到款金额
        uid_ds.setOnceRetrieveCount(1);
        uid_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        manage_ds.setOnceRetrieveCount(1);
        manage_ds.retrieve("id = " + yy_add_account_introduce_list_ds.getValue(i, "user_id") + "");
        achievement_detail_ds.setValue(0, "op_userid", manage_ds.getValue(0, "sixiId"));//运营人员ID
        achievement_detail_ds.setValue(0, "op_username", manage_ds.getValue(0, "realname"));//运营人员
        achievement_detail_ds.setValue(0, "op_departmentid", manage_ds.getValue(0, "class2"));//运营部门
        achievement_detail_ds.setValue(0, "order_type", "5");//业务类型
        achievement_detail_ds.setValue(0, "status", 1);//status
        achievement_detail_ds.setValue(0, "tidan_id", yy_add_account_introduce_list_ds.getValue(i, "task_id"));//提单id
        TaskLadingCn_ds.setOnceRetrieveCount(1);
        TaskLadingCn_ds.retrieve("htID = '" + yy_add_account_introduce_list_ds.getValue(i, "contract_id") + "'");
        // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
        var achievement_amount = getNumberFromSQL2("sixi_oa", "  select case WHEN xfType in  (1,4,2,3) THEN money when contract_nature=0 and admin = 48 or xfType not in (1,2,3,4,5,6)  then 0  when admin in (52,2)or xfType not in (1,2,3,4,5,6) then 0 else money end as money from (select m.*,ma.admin,c.contract_nature,h.xfType from (select sum(Money) as money,max(uid) as uid,max(hid) as hid from money where hid = '" + contract_ds.getValue(0, "id") + "' ) m left join manage ma on ma.id = m.uid LEFT JOIN (select id,clid,case when ISNULL(OldUpgradeId, 0)!=0 then 2 when ISNULL(oldXfId, 0)!=0 then 1 else 0 end as contract_nature from contract ) c on c.id = m.hid  left join htclass h on h.id = c.clid)a ");
        // if (is_wangwang > 0) {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        // }
        var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
        if (is_wangwang == 1) {
            achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        }
        else if (is_wangwang == 2) {
            achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        }
        achievement_detail_ds.setValue(0, "achievement_amount", achievement_amount);//业绩金额
        achievement_detail_ds.setValue(0, "is_zdyy", TaskLadingCn_ds.getValue(0, "isSetYY") || 0);//是否指定运营
        achievement_detail_ds.setValue(0, "job_code", achievement_ds.getValue(0, "job_code"));//作业项目
        achievement_detail_ds.setValue(0, "jobrole_code", achievement_ds.getValue(0, "jobrole_code"));//作业角色
        achievement_detail_ds.setValue(0, "jobtype_code", achievement_ds.getValue(0, "jobtype_code"));//绩效项目
        achievement_detail_ds.setValue(0, "contract_id", yy_add_account_introduce_list_ds.getValue(i, "contract_id"));//合同id
        achievement_detail_ds.setValue(0, "is_add", 0);//是否手动添加
        achievement_detail_ds.setValue(0, "is_xiugai", 0);//是否修改
    }
    if (achievement_detail_ds.update(true)) {
        ret.success = true;
        ret.message = "拉取成功";

    } else {
        ret.message = achievement_detail_ds.getError().getMessage();
    }
    return ret;
}

//转介绍
function tojieshao(gguid, mDate) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }
    var achievement_ds = newDataStore("work", "select * from achievement where gguid='" + gguid + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    if (achievement_ds.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var achievement_detail_ds = newDataStore("work", "select * from achievement_detail where DATE_FORMAT(mDate,'%Y-%m') = '" + mDate + "' and order_type = 6");
    achievement_detail_ds.setUpdateProperty("achievement_detail", "id", "*", "id");
    var row = achievement_detail_ds.retrieve();
    if (row > 0) {
        ret.message = "该月份已有数据，不允许插入";
        return ret;
    }
    var yy_add_account_introduce_list_ds = newDataStore("sixi_oa_pg", "select * from achievement.yy_add_account_introduce_list_history where report_type = 2 and report_time  = '" + mDate + "'and settle_status = 1");
    var row2 = yy_add_account_introduce_list_ds.retrieve();
    var contract_ds = newDataStore("sixi_oa", "select id,nid,clid,numbers,htmoney,startime,endtime from contract ");
    // var contract2_ds = newDataStore("sixi_oa","select clid from contract where id");
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    var uid_ds = newDataStore("sixi_oa", "select uid from money");
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    var aliuser_ds = newDataStore("sixi_oa", "SELECT username FROM aliuser");
    println("++++:" + row2)
    for (var i = 0; i < row2; i++) {
        var contract_billno = yy_add_account_introduce_list_ds.getString(i, "numbers");
        var row = achievement_detail_ds.insertRow(0);
        achievement_detail_ds.setValue(0, "id", newGuid());
        achievement_detail_ds.setValue(0, "gguid", gguid);
        achievement_detail_ds.setValue(0, "contract_billno", contract_billno);//合同编号
        achievement_detail_ds.setValue(0, "mdate", mDate + "-01");//业绩月份
        achievement_detail_ds.setValue(0, "wldw_name", yy_add_account_introduce_list_ds.getValue(i, "company_name"));//客户名称
        contract_ds.setOnceRetrieveCount(1);
        contract_ds.retrieve("numbers = '" + contract_billno + "'");
        achievement_detail_ds.setValue(0, "wldw_id", contract_ds.getValue(0, "nid"));//客户id
        achievement_detail_ds.setValue(0, "contract_amount", contract_ds.getValue(0, "htmoney"));//合同金额
        achievement_detail_ds.setValue(0, "contract_starttime", yy_add_account_introduce_list_ds.getValue(i, "contract_start_time"));//合同开始时间
        achievement_detail_ds.setValue(0, "contract_endtime", yy_add_account_introduce_list_ds.getValue(i, "contract_end_time"));//合同结束时间
        aliuser_ds.setOnceRetrieveCount(1);
        aliuser_ds.retrieve("nid = '" + contract_ds.getValue(0, "nid") + "'");
        achievement_detail_ds.setValue(0, "store_loginname", aliuser_ds.getValue(0, "username"));//店铺账号
        htlx2_ds.setOnceRetrieveCount(1);
        htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
        achievement_detail_ds.setValue(0, "htlx2", htlx2_ds.getValue(0, "code"));//合同类型id
        achievement_detail_ds.setValue(0, "htlx2_name", htlx2_ds.getValue(0, "name"));//合同类型名称
        achievement_detail_ds.setValue(0, "htlx", htlx2_ds.getValue(0, "htlx"));//业务类型
        money_ds.setOnceRetrieveCount(1);
        money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        achievement_detail_ds.setValue(0, "payment_amount", money_ds.getValue(0, "amount"));//到款金额
        uid_ds.setOnceRetrieveCount(1);
        uid_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        manage_ds.setOnceRetrieveCount(1);
        manage_ds.retrieve("id = " + yy_add_account_introduce_list_ds.getValue(i, "user_id") + "");
        achievement_detail_ds.setValue(0, "op_userid", manage_ds.getValue(0, "sixiId"));//运营人员ID
        achievement_detail_ds.setValue(0, "op_username", manage_ds.getValue(0, "realname"));//运营人员
        achievement_detail_ds.setValue(0, "op_departmentid", manage_ds.getValue(0, "class2"));//运营部门
        // contract2_ds.setOnceRetrieveCount(1);
        // contract2_ds.retrieve();
        // if(contract2_ds.getValue(0,"clid")){

        // }
        achievement_detail_ds.setValue(0, "order_type", "6");//业务类型
        achievement_detail_ds.setValue(0, "status", 1);//status
        achievement_detail_ds.setValue(0, "tidan_id", yy_add_account_introduce_list_ds.getValue(i, "task_id"));//提单id
        TaskLadingCn_ds.setOnceRetrieveCount(1);
        TaskLadingCn_ds.retrieve("htID = '" + yy_add_account_introduce_list_ds.getValue(i, "contract_id") + "'");
        // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
        var achievement_amount = getNumberFromSQL2("sixi_oa", " select case WHEN xfType in  (1,4,2,3) THEN money when contract_nature=0 and admin = 48 or xfType not in (1,2,3,4,5,6)  then 0  when admin in (52,2)or xfType not in (1,2,3,4,5,6) then 0 else money end as money from (select m.*,ma.admin,c.contract_nature,h.xfType from (select sum(Money) as money,max(uid) as uid,max(hid) as hid from money where hid = '" + contract_ds.getValue(0, "id") + "' ) m left join manage ma on ma.id = m.uid LEFT JOIN (select id,clid,case when ISNULL(OldUpgradeId, 0)!=0 then 2 when ISNULL(oldXfId, 0)!=0 then 1 else 0 end as contract_nature from contract ) c on c.id = m.hid  left join htclass h on h.id = c.clid)a ");
        // if (is_wangwang > 0) {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        // }
        var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
        if (is_wangwang == 1) {
            achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        }
        else if (is_wangwang == 2) {
            achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        }
        achievement_detail_ds.setValue(0, "achievement_amount", achievement_amount);//业绩金额
        achievement_detail_ds.setValue(0, "is_zdyy", TaskLadingCn_ds.getValue(0, "isSetYY") || 0);//是否指定运营
        achievement_detail_ds.setValue(0, "job_code", achievement_ds.getValue(0, "job_code"));//作业项目
        achievement_detail_ds.setValue(0, "jobrole_code", achievement_ds.getValue(0, "jobrole_code"));//作业角色
        achievement_detail_ds.setValue(0, "jobtype_code", achievement_ds.getValue(0, "jobtype_code"));//绩效项目
        achievement_detail_ds.setValue(0, "contract_id", yy_add_account_introduce_list_ds.getValue(i, "contract_id"));//合同id
        achievement_detail_ds.setValue(0, "is_add", 0);//是否手动添加
        achievement_detail_ds.setValue(0, "is_xiugai", 0);//是否修改
    }
    if (achievement_detail_ds.update(true)) {
        ret.success = true;
        ret.message = "拉取成功";

    } else {
        ret.message = achievement_detail_ds.getError().getMessage();
    }
    return ret;
}

//代运营
function dyy(gguid, mDate) {
    var ret = {
        "success": false,
        "message": ''
    }
    if (gguid != currentGUID()) {
        ret.message = '单据信息不符，终止操作1'
        return ret;
    }
    var achievement_ds = newDataStore("work", "select * from achievement where gguid='" + gguid + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    if (achievement_ds.getRowCount() == 0) {
        ret.message = '单据不存在！';
        return ret;
    }
    var achievement_detail_ds = newDataStore("work", "select * from achievement_detail where DATE_FORMAT(mDate,'%Y-%m') = '" + mDate + "' and order_type in (3,4) ");
    achievement_detail_ds.setUpdateProperty("achievement_detail", "id", "*", "id");
    var row = achievement_detail_ds.retrieve();
    var contract_ds = newDataStore("sixi_oa", "select *,case when ISNULL(OldUpgradeId, 0)!=0 then OldUpgradeId when ISNULL(oldXfId, 0)!=0 then oldXfId else 0 end as previous_contract_id from contract ");
    var contract2_ds = newDataStore("sixi_oa", "select clid from contract");
    var aliuser_ds = newDataStore("sixi_oa", "SELECT username FROM aliuser");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    var uid_ds = newDataStore("sixi_oa", "select uid from money");
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn");
    if (row > 0) {
        ret.message = "该月份已有数据，不允许插入";
        return ret;
    }
    var yy_dyw_list_ds = newDataStore("sixi_oa_pg", "select * from achievement.yy_dyw_list_history where report_time = '" + mDate + "'and settle_status = 1");
    var row2 = yy_dyw_list_ds.retrieve();
    for (var i = 0; i < row2; i++) {
        var contract_billno = yy_dyw_list_ds.getString(i, "numbers");
        var row = achievement_detail_ds.insertRow(0);
        achievement_detail_ds.setValue(0, "id", newGuid());
        achievement_detail_ds.setValue(0, "gguid", gguid);
        achievement_detail_ds.setValue(0, "contract_billno", contract_billno);//合同编号
        achievement_detail_ds.setValue(0, "mdate", mDate + "-01");//业绩月份
        achievement_detail_ds.setValue(0, "wldw_name", yy_dyw_list_ds.getValue(i, "company_name"));//客户名称
        contract_ds.setOnceRetrieveCount(1);
        contract_ds.retrieve("numbers = '" + contract_billno + "'");
        achievement_detail_ds.setValue(0, "wldw_id", contract_ds.getValue(0, "nid"));//客户id
        achievement_detail_ds.setValue(0, "contract_amount", contract_ds.getValue(0, "htmoney"));//合同金额
        achievement_detail_ds.setValue(0, "contract_starttime", yy_dyw_list_ds.getValue(i, "contract_start_time"));//合同开始时间
        achievement_detail_ds.setValue(0, "contract_endtime", yy_dyw_list_ds.getValue(i, "contract_end_time"));//合同结束时间
        aliuser_ds.setOnceRetrieveCount(1);
        aliuser_ds.retrieve("nid = '" + contract_ds.getValue(0, "nid") + "'");
        achievement_detail_ds.setValue(0, "store_loginname", aliuser_ds.getValue(0, "username"));//店铺账号
        htlx2_ds.setOnceRetrieveCount(1);
        htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
        achievement_detail_ds.setValue(0, "htlx2", htlx2_ds.getValue(0, "code"));//合同类型id
        achievement_detail_ds.setValue(0, "htlx2_name", htlx2_ds.getValue(0, "name"));//合同类型名称
        achievement_detail_ds.setValue(0, "htlx", htlx2_ds.getValue(0, "htlx"));//业务类型
        money_ds.setOnceRetrieveCount(1);
        money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        achievement_detail_ds.setValue(0, "payment_amount", money_ds.getValue(0, "amount"));//到款金额
        uid_ds.setOnceRetrieveCount(1);
        uid_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
        manage_ds.setOnceRetrieveCount(1);
        manage_ds.retrieve("id = " + yy_dyw_list_ds.getValue(i, "user_id") + "");
        achievement_detail_ds.setValue(0, "op_userid", manage_ds.getValue(0, "sixiId"));//运营人员ID
        achievement_detail_ds.setValue(0, "op_username", manage_ds.getValue(0, "realname"));//运营人员
        achievement_detail_ds.setValue(0, "op_departmentid", manage_ds.getValue(0, "class2"));//运营部门
        achievement_detail_ds.setValue(0, "status", 1);//status
        // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
        var achievement_amount = getNumberFromSQL2("sixi_oa", " select case WHEN xfType in  (1,4,2,3) THEN money when contract_nature=0 and admin = 48 or xfType not in (1,2,3,4,5,6)  then 0  when admin in (52,2)or xfType not in (1,2,3,4,5,6) then 0 else money end as money from (select m.*,ma.admin,c.contract_nature,h.xfType from (select sum(Money) as money,max(uid) as uid,max(hid) as hid from money where hid = '" + contract_ds.getValue(0, "id") + "' ) m left join manage ma on ma.id = m.uid LEFT JOIN (select id,clid,case when ISNULL(OldUpgradeId, 0)!=0 then 2 when ISNULL(oldXfId, 0)!=0 then 1 else 0 end as contract_nature from contract ) c on c.id = m.hid  left join htclass h on h.id = c.clid)a ");
        TaskLadingCn_ds.setOnceRetrieveCount(1);
        TaskLadingCn_ds.retrieve("htID = '" + yy_dyw_list_ds.getValue(i, "contract_id") + "'");
        print("is_wangwang----" + is_wangwang);
        print("contract_id-------" + yy_dyw_list_ds.getValue(i, "contract_id"));
        print("isSetYY-----" + TaskLadingCn_ds.getValue(0, "isSetYY"));
        print("TaskLadingCn_ds----" + TaskLadingCn_ds.getRowCount());
        // if (is_wangwang > 0) {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        // }
        // else {
        //     achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        // }
        var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
        if (is_wangwang == 1) {
            achievement_detail_ds.setValue(0, "is_wangwang", 1);//是否登录旺旺
        }
        else if (is_wangwang == 2) {
            achievement_detail_ds.setValue(0, "is_wangwang", 0);//是否登录旺旺
        }
        achievement_detail_ds.setValue(0, "is_zdyy", TaskLadingCn_ds.getValue(0, "isSetYY") || 0);//是否指定运营
        achievement_detail_ds.setValue(0, "job_code", achievement_ds.getValue(0, "job_code"));//作业项目
        achievement_detail_ds.setValue(0, "jobrole_code", achievement_ds.getValue(0, "jobrole_code"));//作业角色
        achievement_detail_ds.setValue(0, "jobtype_code", achievement_ds.getValue(0, "jobtype_code"));//绩效项目
        achievement_detail_ds.setValue(0, "contract_id", yy_dyw_list_ds.getValue(i, "contract_id"));//合同id
        achievement_detail_ds.setValue(0, "is_add", 0);//是否手动添加
        achievement_detail_ds.setValue(0, "is_xiugai", 0);//是否修改
        if (yy_dyw_list_ds.getValue(i, "xf_dyw_num") != 0) {
            contract2_ds.setOnceRetrieveCount(1);
            contract2_ds.retrieve("id = " + contract_ds.getInt(0, "previous_contract_id") + "");
            htlx2_ds.setOnceRetrieveCount(1);
            htlx2_ds.retrieve("code = " + contract2_ds.getInt(0, "clid") + "");
            if (htlx2_ds.getInt(0, "htlx") != 1) {
                achievement_detail_ds.setValue(0, "order_type", 4);//代运营续费
                achievement_detail_ds.setValue(0, "achievement_amount", 0);//业绩金额
            }
            else {
                achievement_detail_ds.setValue(0, "order_type", 3);//代运营新单
                achievement_detail_ds.setValue(0, "achievement_amount", achievement_amount);//业绩金额
                achievement_detail_ds.setValue(0, "previous_contract_id", contract_ds.getValue(0, "previous_contract_id"));//上一份合同id
            }
        }
        else {
            achievement_detail_ds.setValue(0, "order_type", 3);//单代运营新单
            achievement_detail_ds.setValue(0, "achievement_amount", achievement_amount);//业绩金额
            achievement_detail_ds.setValue(0, "previous_contract_id", contract_ds.getValue(0, "previous_contract_id"));//上一份合同id
        }
    }
    if (achievement_detail_ds.update(true)) {
        ret.success = true;
        ret.message = "拉取成功";

    } else {
        ret.message = achievement_detail_ds.getError().getMessage();
    }
    return ret;
}

function insertInto(newValue) {
    var contract_ds = newDataStore("sixi_oa", "select *,case when ISNULL(OldUpgradeId, 0)!=0 then OldUpgradeId when ISNULL(oldXfId, 0)!=0 then oldXfId else 0 end as previous_contract_id,dbo.fy_GetEndTimeByContractID ( case when ISNULL(OldUpgradeId, 0)!=0 then OldUpgradeId when ISNULL(oldXfId, 0)!=0 then oldXfId else 0 end ) as previous_contract_endtime from contract where id = '" + newValue + "'");
    contract_ds.retrieve();
    print("contract_ds:" + contract_ds.retrieve());
    print("previous_contract_id----" + contract_ds.getValue(0, "previous_contract_id"));

    // var a = getIntFromSQL2("work", "select contract_id from achievement_detail where contract_id = '" + newValue + "'");
    // if (a != 0) {
    //     return false;
    // }
    var b = getIntFromSQL2("sixi_oa", "select count(*) from htclass where xfType in (1,2,3,4,5) and id = '" + contract_ds.getValue(0, "clid") + "'");
    print("b:" + b);
    var TaskLadingCn_ds = newDataStore("sixi_oa", "select * from TaskLadingCn where htID = '" + contract_ds.getValue(0, "id") + "' and speed != 4");
    TaskLadingCn_ds.setOnceRetrieveCount(1);
    TaskLadingCn_ds.retrieve();
    var news_ds = newDataStore("sixi_oa", "select title,kfid from news where id = '" + contract_ds.getValue(0, "nid") + "'");
    news_ds.setOnceRetrieveCount(1);
    news_ds.retrieve();
    var manage_ds = newDataStore("sixi_oa", "select id,username,admin,class2,realname,sixiId from manage");
    manage_ds.setOnceRetrieveCount(1);
    if (b > 0) {
        manage_ds.retrieve("id = " + news_ds.getValue(0, "kfid") + "");
        print("news_ds.kfid--------" + news_ds.getValue(0, "kfid"));
        print("manage_ds-----news_ds:" + manage_ds.retrieve("id = " + news_ds.getValue(0, "kfid") + ""));
    }
    else {
        manage_ds.retrieve("id = " + TaskLadingCn_ds.getValue(0, "KfId") + "");
        print("TaskLadingCn_ds.KfId------" + TaskLadingCn_ds.getValue(0, "KfId"));
        print("manage_ds-----TaskLadingCn_ds:" + manage_ds.retrieve("id = " + TaskLadingCn_ds.getValue(0, "KfId") + ""));
    }
    var achievement_ds = newDataStore("work", "select * from achievement where gguid = '" + currentGUID() + "'");
    achievement_ds.setOnceRetrieveCount(1);
    achievement_ds.retrieve();
    var aliuser_ds = newDataStore("sixi_oa", "SELECT username FROM aliuser");
    aliuser_ds.setOnceRetrieveCount(1);
    aliuser_ds.retrieve("nid = '" + contract_ds.getValue(0, "nid") + "'");
    var htlx2_ds = newDataStore("os", "select * from htlx2");
    htlx2_ds.setOnceRetrieveCount(1);
    htlx2_ds.retrieve("code = " + contract_ds.getInt(0, "clid") + "");
    var money_ds = newDataStore("sixi_oa", "select sum(Money) as amount from money");
    money_ds.setOnceRetrieveCount(1);
    money_ds.retrieve("hid = " + contract_ds.getValue(0, "id") + "");
    var contract2_ds = newDataStore("sixi_oa", "select clid from contract");
    var param = { mdate: formatDate(achievement_ds.getValue(0, "mdate"), "yyyy-MM-01") };//业绩月份
    param.id = newGuid();
    param.gguid = currentGUID();
    param.wldw_id = contract_ds.getInt(0, "nid");//客户id
    param.contract_id = contract_ds.getInt(0, "id");//合同id
    param.store_loginname = aliuser_ds.getString(0, "username");//店铺账号
    param.contract_amount = contract_ds.getValue(0, "htmoney");//合同金额
    param.contract_starttime = formatDate(contract_ds.getValue(0, "startime"), "yyyy-MM-dd");//合同开始时间
    param.contract_endtime = formatDate(contract_ds.getValue(0, "endtime"), "yyyy-MM-dd");//合同结束时间
    param.htlx2 = htlx2_ds.getInt(0, "code");//合同类型id
    param.htlx2_name = htlx2_ds.getString(0, "name");//合同类型名称
    param.htlx = htlx2_ds.getInt(0, "htlx");//业务类型
    param.payment_amount = money_ds.getValue(0, "amount");//到款金额
    param.status = 1;//status
    param.job_code = achievement_ds.getString(0, "job_code");//作业项目
    param.jobrole_code = achievement_ds.getString(0, "jobrole_code");//作业角色
    param.jobtype_code = achievement_ds.getString(0, "jobtype_code");//绩效项目
    param.op_userid = manage_ds.getInt(0, "id");//运营人员id
    param.op_username = manage_ds.getString(0, "realname");//运营人员
    param.op_departmentid = manage_ds.getInt(0, "class2");//运营部门
    param.is_zdyy = TaskLadingCn_ds.getInt(0, "isSetYY") || 0;//是否指定运营
    // var is_wangwang = getIntFromSQL2("sixi_oa", " select count(*) from custom_wwkf where customid = '" + contract_ds.getValue(0, "nid") + "' and endtime is null");
   
    var achievement_amount = getNumberFromSQL2("sixi_oa", "  select case WHEN xfType in  (1,4,2,3) THEN money when contract_nature=0 and admin = 48 or xfType not in (1,2,3,4,5,6)  then 0  when admin in (52,2) and class2 not in (1223,1224) or xfType not in (1,2,3,4,5,6) then 0 else money end as money from (select m.*,ma.admin,ma.class2,c.contract_nature,h.xfType from (select sum(Money) as money,max(uid) as uid,max(hid) as hid from money where hid = '" + newValue + "' ) m left join manage ma on ma.id = m.uid LEFT JOIN (select id,clid,case when ISNULL(OldUpgradeId, 0)!=0 then 2 when ISNULL(oldXfId, 0)!=0 then 1 else 0 end as contract_nature from contract ) c on c.id = m.hid  left join htclass h on h.id = c.clid)a ");
    print("contract_ds.clid---------" + contract_ds.getInt(0, "clid"));
    print("achievement_amount--------" + achievement_amount);
    if (contract_ds.getInt(0, "clid") == 23 || contract_ds.getInt(0, "clid") == 33 || contract_ds.getInt(0, "clid") == 42) {
        param.achievement_amount = 0;//业绩金额
    }
    else {
        param.achievement_amount = achievement_amount;//业绩金额
    }
    print("param.achievement_amount-------" + param.achievement_amount);
    // if (is_wangwang > 0) {
    //     param.is_wangwang = 1;//是否登旺旺
    // }
    // else {
    //     param.is_wangwang = 0;//是否登旺旺
    // }
    var is_wangwang = getIntFromSQL2("sixi_oa", " select news from custom_wwkf where id = '" + contract_ds.getValue(0, "nid") + "' ");
    if (is_wangwang == 1) {
        param.is_wangwang = 1;//是否登旺旺
    }
    else if (is_wangwang == 2) {
        param.is_wangwang = 0;//是否登旺旺
    }
    param.wldw_name = news_ds.getValue(0, "title");//客户名称
    param.previous_contract_id = contract_ds.getInt(0, "previous_contract_id");//上一份合同id
    param.previous_contract_endtime = formatDate(contract_ds.getValue(0, "previous_contract_endtime"), "yyyy-MM-dd");//上一份合同到期时间
    param.contracft_stopdate = formatDate(contract_ds.getValue(0, "stoptime"), "yyyy-MM-dd");//合同停止时间
    print(JSON.stringify(param));
    return JSON.stringify(param);
}

function getdatafrom(gguid, mDate) {
    runTask("capture_add_or_introduce_operation_form", { "gguid": gguid, "sales_yearmonth": mDate });
    runTask("capture_new_form", { "gguid": gguid, "sales_yearmonth": mDate });
    runTask("capture_renewal_form", { "gguid": gguid, "sales_yearmonth": mDate });
    runTask("capture_agent_operation_form", { "gguid": gguid, "sales_yearmonth": mDate });
    runTask("capture_special_operation_form", { "gguid": gguid, "sales_yearmonth": mDate });
}

function getSQL(str) {
    return decrypt(str, "zeng.jun");
}


id: 60d0a4a20c74a046decf1b26
scriptid: 60d0a25f0c74a046decf1aaa
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 22:41:30.000
script:
function main(arg)
{
    var t1=  createArchive("dzpz", '' , true);
    var t2=  createArchive("dzpz", '' , true);
    
    var source=[];
    source.push( t1.data);
    source.push(t2.data);

    return createZipFileWith("测试压缩.zip" ,source);

}


id: 60d0a4a20c74a046decf1b2e
scriptid: 60d0a25f0c74a046decf1aaa
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 22:42:08.000
script:
function main(arg)
{
    var t1=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    var t2=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    
    var source=[];
    source.push( t1.data);
    source.push(t2.data);

    return createZipFileWith("测试压缩.zip" ,source);

}


id: 60d0a4a20c74a046decf1b36
scriptid: 60d0a25f0c74a046decf1aaa
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 22:42:34.000
script:
function main(arg)
{
    var t1=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    var t2=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    
    var source=[];
    source.push( t1.data);
    source.push(t2.data);

    println( JSON.stringify(source));

    return createZipFileWith("测试压缩.zip" ,source);

}


id: 60d0a4a20c74a046decf1b3f
scriptid: 60d0a25f0c74a046decf1aaa
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 22:46:49.000
script:
function main(arg)
{
    var t1=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    println( JSON.stringify(t1));

    var t2=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    println( JSON.stringify(t2));
    
    var source=[];
    source.push( t1.data);
    source.push(t2.data);

    println( JSON.stringify(source));

    return createZipFileWith("测试压缩.zip" ,source);

}


id: 60d0a6580c74a046decf1b47
scriptid: 60d0a25f0c74a046decf1aaa
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.21 23:16:11.000
script:
function main(arg)
{
    var t1=  createArchive("dzpz", '60c9b874993292baa316b7cc' , true);
    println( JSON.stringify(t1));

    var t2=  createArchive("dzpz", '60c9b874993292baa316b7c6' , true);
    println( JSON.stringify(t2));
    
    var source=[];
    source.push( t1.data);
    source.push(t2.data);

    println( JSON.stringify(source));

    return createZipFileWith("测试压缩.zip" ,source);

}


id: 60d0a6a5993254220bd859d3
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:52:35.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL('work', "delete from pzdjex where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0a6a5993254220bd859df
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:53:34.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_import_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
        // alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0a6a5993254220bd859e5
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:54:05.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
        // alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0a6a5993254220bd859eb
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:57:22.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
         alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0a6a5993254220bd859f3
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:59:35.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    return { 'success': false, 'message': '由于您不是制单人，不允许对当前单据做导入操作!' }
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL('work', "delete from pzdjex where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0a6a5993254220bd859fb
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 22:59:42.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    return { 'success': false, 'message': '由于您不是制单人，不允许对当前单据做导入操作!' }
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL('work', "delete from pzdjex where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0a6a5993254220bd85a10
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:04:34.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    if (ds.getString(0, "userid") != currentUserId()) {
        return { 'success': false, 'message': '由于您不是制单人，不允许对当前单据做导入操作!' }
    }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }
    }
    // console.dir(data);

    var gguid = currentGUID();
    var lastmodifieddate = newDate();

    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }

    if (ds.update(true)) {
        // $alert('导入完成');
        return { success: true, message: '' };
    } else {
        return { success: false, message: ds.getError().getMessage() };
    }

}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0a6a5993254220bd85a1b
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:08:36.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0ab9e993254220bd85a33
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:15:13.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0ab9e993254220bd85a39
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:15:36.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
         //alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0ab9e993254220bd85a3f
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:17:19.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
         //alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            toastr.info(JSON.stringify(ret));

            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0ab9e993254220bd85a45
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:17:22.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
        //alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            toastr.info(JSON.stringify(ret));

            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0ab9e993254220bd85a4b
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:19:41.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

}

//导入excel文件
function cb_importXLS_onClick(sheet, cell, button) {

    //  $alert("功能调整中，暂停使用");
    //  if( currentUserId()!=1) return;

    book.readXLS(function (data) {
        //alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        setTimeout(function () {
            var ret = sys_importExcelData(data);
            toastr.info(JSON.stringify(ret));
            alert(ret.message);

            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
            } else {
                toastr.warning(ret.message);
            }

        }, 100);
    });
}


id: 60d0ab9e993254220bd85a6f
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:35:11.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
   // return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        if(sys_excelSafeValue(excelSheet, row, 1)=='') break; //空行，直接结束
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0b29e993254220bd85a89
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:39:10.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
   // return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData.Sheet1;

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        if(sys_excelSafeValue(excelSheet, row, 1)==null) break; //空行，直接结束
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0b29e993254220bd85a95
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:43:34.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
   // return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet = excelData[ Object.keys(excelData)[0] ];
    
    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        if(sys_excelSafeValue(excelSheet, row, 1)==null) break; //空行，直接结束
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0b29e993254220bd85aa0
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:45:36.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
   // return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet;
    for( var p in excelData)
    {
        excelSheet= excelData[p];
    }

    

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelData.Sheet1.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        if(sys_excelSafeValue(excelSheet, row, 1)==null) break; //空行，直接结束
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d0b29e993254220bd85aab
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.21 23:46:29.000
script:
//后端导入excel数据包
function sys_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
   // return { success: false, message: excelData }
    var dsn = 'pz';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }
    // if (ds.getString(0, "userid") != currentUserId()) {
    //     ret.message = '由于您不是制单人，不允许对当前单据做导入操作!';
    //     return ret;
    // }
    if (ds.getString(0, "verifiername") != '') {
        ret.message = '单据已审核，不允许导入操作!';
        return ret;
    }

    runSQL(dsn, "delete from " + tableName + " where gguid='" + currentGUID() + "'");

    //**********************************************
    //导入的标准功能
    var colLabel2ColName = {
        "年度": "y",
        "调整期间": "m",
        "凭证号": "pzh",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "是否已过账": "posted",
        "备注": "bz"
    }


    var excelSheet;
    for( var p in excelData)
    {
        excelSheet= excelData[p];
    }

    

    //分析字段对应关系
    var excelColIndex2ColName = {}; //excel 中的列号对应的中文题头
    var excelColName2ColIndex = {}; //中文题头对应的excel中的列号
    // var colLabel2ColName = {}; //中文题头对应到表的字段名


    var duplicateLabelCount = {};
    var colCount = 50; //最多几个列

    var headRow = 0; //题头在第几行
    var dataStartRow = 1; // 数据行从第几行开始
    //有时可能表头有多行合并，所以要检测一下
    for (var i = 0; i < colCount; i++) {
        var v = trim(sys_excelSafeValue(excelSheet, headRow, i));
        if (v == '')
            continue;
        if (duplicateLabelCount[v] == undefined) {
            duplicateLabelCount[v] = 0;
        }
        duplicateLabelCount[v] = duplicateLabelCount[v] + 1;

        if (duplicateLabelCount[v] > 1)
            v = v + duplicateLabelCount[v];
        //拼上后缀

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }

    println(JSON.toString(excelColName2ColIndex));
    println(JSON.toString(excelColIndex2ColName));

    var RC = excelSheet.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        if(sys_excelSafeValue(excelSheet, row, 1)==null) break; //空行，直接结束
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];
            var dbCol = colLabel2ColName[label];
            if (dbCol != null) {
                oneRowData[dbCol] = sys_excelSafeValue(excelSheet, row, excelCol);
            }
        }

    }
    println(JSON.toString(data));

    // console.dir(data);

    var gguid = currentGUID();
    var userid = currentUserId();
    var username = currentUserName();
    var lastmodifieddate = newDate();
    // println('import_ph:' + import_ph);



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }


    if (ds.update(true)) {
        // $alert('导入完成');
        ret.success = true;
        ret.message = ds.getString(0, "userid");

    } else {
        ret.message = ds.getError().getMessage();
    }

    return ret;
}

function sys_excelSafeValue(sheet, row, col) {
    if (row > sheet.length - 1) return null;
    var dataRow = sheet[row];
    if (dataRow == null) return null;
    if (col > dataRow.length - 1) return null;
    return dataRow[col];

}


id: 60d11f1a0c74cfc41ff8bac8
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.22 07:27:01.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    packageGo('download');
}


function cb_view_onClick()
{
    packageGo('view');
}

function packageGo( action)
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID(), 
    overwrite:true  //如果已存在，则重新生成
    }));
    console.dir(ret);
    if( ret.success)
    {
        let url= ret.data.url_img;
        if( action=='download')  url= url.replace('action=view' , 'action=download');
        openWindow(  url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d170d899326f91203456dc
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:15:18.000
script:
var labelDataInited=false;

/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
    book.showTabOnWhere="top";
    $dzpz_pzbq_ds.reset();
    var s= $dzpz_pz_ds.getString(0,"labeldata");
    if(s=='') s="{}";
    var data= JSON.parse(s);
    if( typeof(data)!='object') data={};
    for( var name in data)
    {
        var value= data[name];
        if( ['凭证号','记帐期'].contains(name)) continue;
        var row= $dzpz_pzbq_ds.insertRow(999);
        $dzpz_pzbq_ds.setValue(row,{name:name, value:value});
    }
    labelDataInited=true;


}

//图片控件初始化之前的处理，注入参数
function imageGridlyBeforeInit(sheet, name, data)
{
    sheet.getBrick(name).config.uploadButtonDisabled  =true;
    sheet.getBrick(name).config.deleteButtonDisabled  =true;
}

/**
 * 数据集中的数据发生变化
 * @param dsname 数据集名称
 * @param row   数据行号
 * @param col    字段名
 * @param oldValue   原值
 * @param newValue  新值
 */
function itemChanged (dsname,row, col, oldValue, newValue)
{
    if( dsname=='dzpz_pzbq')
    {
        rebuildLabel();
    }
}


function rebuildLabel()
{
    if(! labelDataInited) return;
    var label={'凭证号':$dzpz_pz_ds.getString(0,"pzh") , '记帐期':$dzpz_pz_ds.getInt(0,"ym") };
    for( var i=0;i<$dzpz_pzbq_ds.rowCount;i++)
    {
        var name= $dzpz_pzbq_ds.getString(i,"name");
        
     var value= $dzpz_pzbq_ds.getString(i,"value");
     if( name=='') continue;
     label[name]=value; 
    }

    $dzpz_pz_ds.setValue(0,"labeldata", JSON.stringify(label));
        
}


function cb_download_onClick()
{
    packageGo('download');
}


function cb_view_onClick()
{
    packageGo('view');
}

function packageGo( action)
{
    var ret=  JSON.parse(runTask("pz_image2pdf" ,{id: currentGUID(), 
    overwrite:false  //如果已存在，不要重新生成
    }));
    console.dir(ret);
    if( ret.success)
    {
        let url= ret.data.url_img;
        if( action=='download')  url= url.replace('action=view' , 'action=download');
        openWindow(  url);
    }else{
        $.alert( ret.message);
    }
}


id: 60d170d899326f91203456ed
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:20:41.000
script:
//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ(id) {
    var ds = newDataStore("pz", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='" + id + "'  order by groupname , info1 asc ");
    var n = ds.retrieve();
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }
    return ret;

}




//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    return runTask("getPZHPrefix" ,{ym:ym});
    
}
//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt( runTask("getPZHLen",{}));
}



//@comment (group=,caption=凭证审核或取消审核,needRightControl=false)
function do_sh(id, sh) {


    if (!isRoleGrantedToUser(currentUserId(), "60c81b135db2d209d074b697")) return { success: false, message: "没有审核权限" };



    var dzpz_ds = newDataStore("pz", "select * from dzpz_pz where id='" + id + "'");
    dzpz_ds.setUpdateProperty("dzpz_pz", "id", "*", "id");
    dzpz_ds.retrieve();
    if (dzpz_ds.getRowCount() == 0) {
        return { success: false, message: "凭证不存在" };
    }
    if (sh) //做审核
    {
        var verifierid = dzpz_ds.getInt(0, "verifierid");
        if (verifierid != 0) return {
            success: true, verifierid: verifierid,
            verifiername: dzpz_ds.getString(0, "verifiername"),
            verifieddate: dzpz_ds.getString(0, "verifieddate"), message: "凭证已审核，不需要重复审核"
        };
        dzpz_ds.setValue(0, "verifierid", currentUserId());
        dzpz_ds.setValue(0, "verifiername", currentUserShowName());
        dzpz_ds.setValue(0, "verifieddate", newDate());

        if (!dzpz_ds.update(true)) return { success: false, message: dzpz_ds.getError().getMessage() };

        //审核后，归档
        runTask("pz_image2pdf" ,{id:id , 
            overwrite:true  //如果已存在，删除并重新生成
            });
        return {
            success: true,
            verifierid: dzpz_ds.getString(0, "verifierid"),
            verifiername: dzpz_ds.getString(0, "verifiername"),
            verifieddate: dzpz_ds.getString(0, "verifieddate")
        };

    } else {
        var verifierid = dzpz_ds.getInt(0, "verifierid");
        println(verifierid);
        if (verifierid == 0) return { success: true, message: "凭证尚未审核，不需要取消审核" };
        if (verifierid != currentUserId()) {
            if (!isRoleGrantedToUser(currentUserId(), "60c81b135db2d209d074b6a7")) {

                return { success: false, message: "必须由审核人或超级审核员来取消审核" };
            }
        }
        dzpz_ds.setValue(0, "verifierid", null);
        dzpz_ds.setValue(0, "verifiername", null);
        dzpz_ds.setValue(0, "verifieddate", null);

        if (!dzpz_ds.update(true)) return { success: false, message: dzpz_ds.getError().getMessage() };
        return { success: true };
    }

}


id: 60d1732d99326f91203456f5
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:20:46.000
script:
//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ(id) {
    var ds = newDataStore("pz", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='" + id + "'  order by groupname , info1 asc ");
    var n = ds.retrieve();
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }
    return ret;

}




//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    return runTask("getPZHPrefix" ,{ym:ym});
    
}
//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt( runTask("getPZHLen",{}));
}



//@comment (group=,caption=凭证审核或取消审核,needRightControl=false)
function do_sh(id, sh) {


    if (!isRoleGrantedToUser(currentUserId(), "60c81b135db2d209d074b697")) return { success: false, message: "没有审核权限" };



    var dzpz_ds = newDataStore("pz", "select * from dzpz_pz where id='" + id + "'");
    dzpz_ds.setUpdateProperty("dzpz_pz", "id", "*", "id");
    dzpz_ds.retrieve();
    if (dzpz_ds.getRowCount() == 0) {
        return { success: false, message: "凭证不存在" };
    }
    if (sh) //做审核
    {
        var verifierid = dzpz_ds.getInt(0, "verifierid");
        if (verifierid != 0) return {
            success: true, verifierid: verifierid,
            verifiername: dzpz_ds.getString(0, "verifiername"),
            verifieddate: dzpz_ds.getString(0, "verifieddate"), message: "凭证已审核，不需要重复审核"
        };
        dzpz_ds.setValue(0, "verifierid", currentUserId());
        dzpz_ds.setValue(0, "verifiername", currentUserShowName());
        dzpz_ds.setValue(0, "verifieddate", newDate());

        if (!dzpz_ds.update(true)) return { success: false, message: dzpz_ds.getError().getMessage() };

        //审核后，归档
        runTask("pz_image2pdf" ,{id:id , 
            overwrite:true  //如果已存在，删除并重新生成
            });
            
        return {
            success: true,
            verifierid: dzpz_ds.getString(0, "verifierid"),
            verifiername: dzpz_ds.getString(0, "verifiername"),
            verifieddate: dzpz_ds.getString(0, "verifieddate")
        };

    } else {
        var verifierid = dzpz_ds.getInt(0, "verifierid");
        println(verifierid);
        if (verifierid == 0) return { success: true, message: "凭证尚未审核，不需要取消审核" };
        if (verifierid != currentUserId()) {
            if (!isRoleGrantedToUser(currentUserId(), "60c81b135db2d209d074b6a7")) {

                return { success: false, message: "必须由审核人或超级审核员来取消审核" };
            }
        }
        dzpz_ds.setValue(0, "verifierid", null);
        dzpz_ds.setValue(0, "verifiername", null);
        dzpz_ds.setValue(0, "verifieddate", null);

        if (!dzpz_ds.update(true)) return { success: false, message: dzpz_ds.getError().getMessage() };
        return { success: true };
    }

}


id: 60d1732d99326f9120345707
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:29:27.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}
 

/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

 

/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick()
{
    showInfoPane("*正在压缩打包...");
    let source=[];
     for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
             source.push($dzpz_pz_ds.getString(i,"id"));
        }

    runTask("打包下载",{fileName: formatDate(newDate(), "yyyyMMddHHmm")+".zip" , source:source },
     function(ret)
     {
         hideInfoPane();
         if( ret.success)
         { 
         openWindow(ret.url);
         }else{
             toastr.error( ret.message);
         }
     })
}


id: 60d1755999326f912034581a
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:33:50.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}
 

/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

 

/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick()
{
    showInfoPane("*正在压缩打包...");
    let ids=[];
     for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
             ids.push($dzpz_pz_ds.getString(i,"id"));
        }

    runTask("打包下载",{fileName: formatDate(newDate(), "yyyyMMddHHmm")+".zip" , ids:ids },
     function(ret)
     {
         hideInfoPane();
         if( ret.success)
         { 
         openWindow(ret.url);
         }else{
             toastr.error( ret.message);
         }
     })
}


id: 60d1769999326f9120345849
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:35:36.000
script:
function main(arg)
{

    var p= JSON.parse(arg);

    var ids=p.ids;

    var source=[];
    for( var i=0;i<ids.length;i++)
    { 
    var t  =  createArchive("dzpz", ids[i] , false);
    source.push( t.data);
    }
    
     

    println( JSON.stringify(source));

    return createZipFileWith( p.fileName  ,source);

}


id: 60d1769999326f9120345855
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:39:32.000
script:
function main(arg) {

    var p = JSON.parse(arg);

    var ids = p.ids;

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t = createArchive("dzpz", ids[i], false);
        source.push(t.data);
    }



    println(JSON.stringify(source));

    return createZipFileWith(p.fileName, source);

}


id: 60d1769999326f912034585d
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:40:28.000
script:
function main(arg) {

    var p = JSON.parse(arg);

    var ids = p.ids;

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t = createArchive("dzpz", ids[i], false);
        source.push(t.data);
    }



    println(JSON.stringify(source));

    var ret= createZipFileWith(p.fileName, source);
    println( JSON.parse(ret));
    return ret; 

}


id: 60d1769999326f9120345865
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:44:29.000
script:
function main(arg) {

    var p = JSON.parse(arg);

    var ids = p.ids;

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t = createArchive("dzpz", ids[i], false);
        source.push(t.data);
    }



    println(JSON.stringify(source));

    var ret= createZipFileWith(p.fileName, source);
    println( ret);
    return ret; 

}


id: 60d1769999326f9120345871
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:51:10.000
script:
function main(arg) {

    var p = JSON.parse(arg);

    var ids = p.ids;

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        source.push(t.data);
    }



    println(JSON.stringify(source));

    var ret= createZipFileWith(p.fileName, source);
    println( ret);
    return ret; 

}


id: 60d1769999326f912034587b
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:52:24.000
script:
function main(arg) {

    var p = JSON.parse(arg);

    var ids = p.ids;

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        source.push(t.data);
    }



    println(JSON.stringify(source));

    var ret= createZipFileWith(p.fileName, source);
    println( JSON.stringify( ret));
    return ret; 

}


id: 60d1769999326f9120345881
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:52:28.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {
    showInfoPane("*正在压缩打包...");
    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
        function (ret) {
            hideInfoPane();
            if (ret.success) {
                openWindow(ret.url);
            } else {
                toastr.error(ret.message);
            }
        })
}


id: 60d17afa99326f9120345887
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:54:03.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {
    showInfoPane("*正在压缩打包...");
    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
        function (ret) {
            ret= JSON.parse(ret);
            hideInfoPane();
            if (ret.success) {
                openWindow(ret.url);
            } else {
                toastr.error(ret.message);
            }
        })
}


id: 60d17afa99326f912034588d
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:56:55.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {
    showInfoPane("*正在压缩打包...");
    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    if( ids.length==0)
    {
        toastr.info("至少选中一张凭证");
        return;
    }

    $confirm('', '确信要将选中的凭证打包下载吗?', function () {

    runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
        function (ret) {
            ret= JSON.parse(ret);
            hideInfoPane();
            if (ret.success) {
                openWindow(ret.url);
            } else {
                toastr.error(ret.message);
            }
        });

    });
}


id: 60d17afa99326f9120345893
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:56:58.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {
    showInfoPane("*正在压缩打包...");
    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    if (ids.length == 0) {
        toastr.info("至少选中一张凭证");
        return;
    }

    $confirm('', '确信要将选中的凭证打包下载吗?', function () {

        runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    openWindow(ret.url);
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}


id: 60d17afa99326f9120345899
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:57:53.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {
    
    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    if (ids.length == 0) {
        toastr.info("至少选中一张凭证");
        return;
    }

    $confirm('', '确信要将选中的凭证打包下载吗?', function () {

        runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
            showInfoPane("*正在压缩打包...");
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    openWindow(ret.url);
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}


id: 60d17afa99326f912034589f
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:58:07.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {

    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    if (ids.length == 0) {
        toastr.info("至少选中一张凭证");
        return;
    }

    $confirm('', '确信要将选中的凭证打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },

            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    openWindow(ret.url);
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}


id: 60d17afa99326f91203458a5
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.22 13:59:25.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



function formOpen() {
    //加载帐套信息及年月
    var corporationid = book.sheet0.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet0.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();

        pzh_prefix = getPZHPrefix(ym);
        book.sheet0.cells("pzh_prefix").setValue(pzh_prefix);


    });

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


}

function cb_check_onClick() {
    smartRetrieve(book.sheet0, "pzh_check", true, false, function () { //检索完后回调
        if ($pzh_check_ds.rowCount == 0) {
            toastr.success("凭证号检测通过");

        } else {
            book.sheet3.popup('fa fa-cog', '缺失的凭证', 250, 350, true, true, {});
        }
    });
}


/**
 * 多行结果集当前焦点行发生变化
 * @param dsname  结果集名称
 * @param row  行号
 */
function currentBindRowChanged(dsname, row) {
    if (dsname == 'dzpz_pz') {
        //重新加载凭证图片列表

        let id = $dzpz_pz_ds.getString(row, "id");
        let pzh = $dzpz_pz_ds.getString(row, "pzh");
        loadPZ(pzh, id);

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.sheet2.getBrick('FJ');
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet2.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}



/**
 * 单元格单击事件
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {

    //通过别名来判断
    if (cell.alias == 'XXX') {

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_pz') {
        if (bind.DBCol == 'c_sh1') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") != 0) return; //已审核，不要再审核
            do_sh1(innerRow);
        }
        if (bind.DBCol == 'c_sh2') {
            if ($dzpz_pz_ds.getInt(innerRow, "verifierid") == 0) return; //没有审核，不需要取消审核
            do_sh2(innerRow);
        }
    }

}

function do_sh1(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    let pzh = $dzpz_pz_ds.getString(innerRow, "pzh");

    do_sh(id, true, function (ret)  //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", ret.verifierid);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", ret.verifiername);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", ret.verifieddate);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "审核成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "取消");

        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}

function do_sh2(innerRow, callback) {
    let id = $dzpz_pz_ds.getString(innerRow, "id");
    do_sh(id, false, function (ret) //后台执行
    {
        if (ret.success) {
            $dzpz_pz_ds.setValue(innerRow, "verifierid", null);
            $dzpz_pz_ds.setValue(innerRow, "verifiername", null);
            $dzpz_pz_ds.setValue(innerRow, "verifieddate", null);
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", "取消成功");
            $dzpz_pz_ds.setValue(innerRow, "c_sh1", "审核");
            $dzpz_pz_ds.setValue(innerRow, "c_sh2", "");


        } else {
            $dzpz_pz_ds.setValue(innerRow, "tipinfo", ret.message);

        }
        if (callback) callback();
    });
}



//@comment (group=工具函数,caption=全选或取消全选)
function seletOrUnSelectAll() {
    //让selection单元格失去编辑焦点，不然再点击，它不会触发单元格的点击事件，因为此时点击的编辑框对象，不会触发单元格的点击
    book.sheet1.View.forceCurrentEditControlGiveUpFocus();

    var v = book.sheet1.cells('selection').getValueInt();

    book.sheet1.paintPermit = false;
    $dzpz_pz_ds.setValueWithTrigger = false;
    for (var i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        $dzpz_pz_ds.setValue(i, "selected", v);
    }
    $dzpz_pz_ds.setValueWithTrigger = true;
    book.sheet1.paintPermit = true;
}


function cb_verify_onClick() {
    $confirm('', '确信要对选中的凭证做审核确认吗?', function () {



        let verifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            verifyCount++;
            showInfoPane("* 正在审核确认...");
            do_sh1(i, function () {
                verifyCount--;
                console.info(verifyCount);
                if (verifyCount == 0) hideInfoPane();
            })
        }


    });
}



function cb_unverify_onClick() {
    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {



        let unverifyCount = 0;
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            unverifyCount++;
            showInfoPane("* 正在取消确认...");
            do_sh2(i, function () {
                unverifyCount--;
                console.info(unverifyCount);
                if (unverifyCount == 0) hideInfoPane();
            });
        }


    });
}


function cb_package_onClick() {

    let ids = [];
    for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
        if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
        ids.push($dzpz_pz_ds.getString(i, "id"));
    }

    if (ids.length == 0) {
        toastr.info("至少选中一张凭证");
        return;
    }

    $confirm('', '确信要将选中的凭证打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        runTask("打包下载", { fileName: formatDate(newDate(), "yyyyMMddHHmm") + ".zip", ids: ids },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    openWindow(ret.url);
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}


id: 60d557b0ebaf5b2c364b965f
scriptid: 609d4b105db2b0a331d6bf04
tablename: app_script
clientip: 192.168.1.176
username: sa
createdate: 2021.06.25 12:14:18.000
script:
//为每个操作员创建一个待归档图片单据 ， 所有单据都先上传到这个单据中做附件
function main(arg) {
    var gguid = '';
    var ds = newDataStore("", "select * from dzpz_imgpool ");
    ds.setUpdateProperty("dzpz_imgpool", "id", "*", "id");
    println ( "currentUserId="+ currentUserId());
    ds.retrieve(" userid='" + currentUserId() + "'");
    println( ds.getSelectLastRetrieved());
    if (ds.getRowCount() == 1) {
        gguid = ds.getString(0, "gguid");
    } else {

        println( "new record");
        ds.insertRow(0);
        gguid = newGUID();
        ds.setValue(0, "id", gguid);
        ds.setValue(0, "gguid", gguid);
        ds.setValue(0, "billno", gguid);
        ds.setValue(0, "billdate", newDate());
        ds.setValue(0, "billtype", '');
        ds.setValue(0, "userid", currentUserId());
        ds.setValue(0, "username", currentUserShowName());
        ds.setValue(0, "deleteflag", 0);
        ds.setValue(0, "blocksize", 128);
        

        if (ds.update(true)) {
            error = ds.getError().getMessage();
            println(error);
            return { success: false, message: error };
        }
    }

    var blockSize=  ds.getInt(0,"blocksize");
    if( blockSize==0) blockSize=128; 

    //提供图片上传的必要的参数
    var config = { "serverIndex": "2", 
                    "dbpool": "default", 
                    "logTable": "dzpz_imgpool_fileupload", 
                    "blockSize": blockSize, 
                    "imgMaxSize": 1920, 
                    "groupName": "附件",
                     "tableName": "dzpz_imgpool", 
                     "gguid": gguid, 
                     "path": "dzpz_imgpool/"+ date2yyyymmdd(newDate(), "/"), 
                     "maxThumbnailSize": 512 ,
                     "responseType":"JSON"  //表示上传成功捂返回 JSON格式的结果
             }

    println(JSON.stringify(config));
    return config; 


}


id: 60d55c9eebaf6f2787524dfe
scriptid: 60a321f05db27838e0c014bf
tablename: app_script
clientip: 192.168.1.176
username: sa
createdate: 2021.06.25 13:28:18.000
script:
//@comment (group=,caption=得到当前操作员待归档图片对应的GGUID,needRightControl=false)
function getImagePoolGGUID() {
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    return JSON.parse(ret).gguid;

}

function getImagePoolBlockSize() {
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    return JSON.parse(ret).blockSize;

}


//@comment (group=,caption=保存当前的缩略图大小,needRightControl=false)
function setImagePoolBlockSize(id, blockSize) {
    runSQL("", " update  dzpz_imgpool set blocksize=" + blockSize + " where gguid='" + id + "'  ");
}


//@comment (group=,caption=得到待归档的图片清单,needRightControl=true)
function loadImagePoolData() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

//排除掉回收站的图片
    var sql= "select * from " + config.logTable + "  where  gguid='" + config.gguid + 
    "'  and ifnull(info2,'')=''  order by info1 , filename asc ";
    println( sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序
    var n = ds.retrieve();
   
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return  { success:true,  data:ret};

}


//@comment (group=,caption=保存监控目录设置,needRightControl=false)
function setMonitePath(hostName, path) {
    var ds = newDataStore("", "select * from dzpz_client");
    ds.setUpdateProperty("dzpz_client","id","*","id");
    ds.retrieve(" hostname='" + hostName + "'");
    if (ds.getRowCount() == 0) {
        var newid = newGUID();
        ds.insertRow(0);
        ds.setValue(0, "id", newid);
        ds.setValue(0, "gguid", newid);
        ds.setValue(0, "billno", newid);
        ds.setValue(0, "userid", 1);
        ds.setValue(0, "username", '管理员');
        ds.setValue(0, "billtype", '');
        ds.setValue(0, "hostname", hostName);
    }
    ds.setValue(0, "path", path);
    ds.update(true);
    println( ds.getError().getMessage());

}


//@comment (group=,caption=获取指定机器的监控目录,needRightControl=false)
function  getMonitePath(hostName)
{
    return   getStringFromSQL("select path from dzpz_client where  hostname='" + hostName + "'");
}


//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ( id)
{
    var ds= newDataStore("pz", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='"+id+"'  order by groupname , info1 asc ");
    var n=ds.retrieve();
    var ret=[];
    for( var i=0;i<n;i++)
    {
        ret.push(  JSON.parse(  ds.getJSONRow(i, true)));
    }
    return ret; 

}



//@comment (group=,caption=把凭证中的附件图片回归到待归档池中,needRightControl=false)
function putImageBackToPool( id )
{
    println( id);
    return  JSON.parse( runTask("凭证附件移除", {id:id} ));
}


//@comment (group=,caption=追加图片到凭证中,needRightControl=false)
function addImageToPZ( pzid , images)
{
    return  JSON.parse( runTask("追加图片到凭证中",{pzid:pzid, images:images}));
}

function deletePZAndPutBackToPool(id)
{
     return  JSON.parse( runTask("删除凭证所有图片回归池中", {id:id} ));
}

function  moveImageToRecycle(id)
{
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));
    runSQL(config.dbpool,  " update "+config.logTable+ " set info2='回收站' where id='"+id+"'  ",true);


}

//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    return runTask("getPZHPrefix" ,{ym:ym});
    
}
//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt( runTask("getPZHLen",{}));
}

function getLastPZH( corporationid , ym)
{
    var t= getStringFromSQL2( "pz" , "select max(pzh) from dzpz_pz where corporationid='"+corporationid+"' and ym="+ym);
    return t; 
}


function do_imageRotate( id , rt)
{
    var ret= imageRotate("","dzpz_imgpool_fileupload" , id , rt);
    println( JSON.stringify(ret));
    return ret; 
}


id: 60d55c9eebaf6f2787524e06
scriptid: 60a321f05db27838e0c014bf
tablename: app_script
clientip: 192.168.1.176
username: sa
createdate: 2021.06.25 13:28:25.000
script:
//@comment (group=,caption=得到当前操作员待归档图片对应的GGUID,needRightControl=false)
function getImagePoolGGUID() {
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    return JSON.parse(ret).gguid;

}

function getImagePoolBlockSize() {
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    return JSON.parse(ret).blockSize;

}


//@comment (group=,caption=保存当前的缩略图大小,needRightControl=false)
function setImagePoolBlockSize(id, blockSize) {
    runSQL("", " update  dzpz_imgpool set blocksize=" + blockSize + " where gguid='" + id + "'  ");
}


//@comment (group=,caption=得到待归档的图片清单,needRightControl=true)
function loadImagePoolData() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

//排除掉回收站的图片
    var sql= "select * from " + config.logTable + "  where  gguid='" + config.gguid + 
    "'  and ifnull(info2,'')=''  order by info1 asc, filename asc ";
    println( sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序
    var n = ds.retrieve();
   
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return  { success:true,  data:ret};

}


//@comment (group=,caption=保存监控目录设置,needRightControl=false)
function setMonitePath(hostName, path) {
    var ds = newDataStore("", "select * from dzpz_client");
    ds.setUpdateProperty("dzpz_client","id","*","id");
    ds.retrieve(" hostname='" + hostName + "'");
    if (ds.getRowCount() == 0) {
        var newid = newGUID();
        ds.insertRow(0);
        ds.setValue(0, "id", newid);
        ds.setValue(0, "gguid", newid);
        ds.setValue(0, "billno", newid);
        ds.setValue(0, "userid", 1);
        ds.setValue(0, "username", '管理员');
        ds.setValue(0, "billtype", '');
        ds.setValue(0, "hostname", hostName);
    }
    ds.setValue(0, "path", path);
    ds.update(true);
    println( ds.getError().getMessage());

}


//@comment (group=,caption=获取指定机器的监控目录,needRightControl=false)
function  getMonitePath(hostName)
{
    return   getStringFromSQL("select path from dzpz_client where  hostname='" + hostName + "'");
}


//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ( id)
{
    var ds= newDataStore("pz", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='"+id+"'  order by groupname , info1 asc ");
    var n=ds.retrieve();
    var ret=[];
    for( var i=0;i<n;i++)
    {
        ret.push(  JSON.parse(  ds.getJSONRow(i, true)));
    }
    return ret; 

}



//@comment (group=,caption=把凭证中的附件图片回归到待归档池中,needRightControl=false)
function putImageBackToPool( id )
{
    println( id);
    return  JSON.parse( runTask("凭证附件移除", {id:id} ));
}


//@comment (group=,caption=追加图片到凭证中,needRightControl=false)
function addImageToPZ( pzid , images)
{
    return  JSON.parse( runTask("追加图片到凭证中",{pzid:pzid, images:images}));
}

function deletePZAndPutBackToPool(id)
{
     return  JSON.parse( runTask("删除凭证所有图片回归池中", {id:id} ));
}

function  moveImageToRecycle(id)
{
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));
    runSQL(config.dbpool,  " update "+config.logTable+ " set info2='回收站' where id='"+id+"'  ",true);


}

//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    return runTask("getPZHPrefix" ,{ym:ym});
    
}
//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt( runTask("getPZHLen",{}));
}

function getLastPZH( corporationid , ym)
{
    var t= getStringFromSQL2( "pz" , "select max(pzh) from dzpz_pz where corporationid='"+corporationid+"' and ym="+ym);
    return t; 
}


function do_imageRotate( id , rt)
{
    var ret= imageRotate("","dzpz_imgpool_fileupload" , id , rt);
    println( JSON.stringify(ret));
    return ret; 
}


id: 60d58c32ebaf6f2787524f0b
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.25 16:03:52.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            do_trush(selection);
        });

}

function do_trush( selection)
{
    console.dir( selection);

}


id: 60d58c32ebaf6f2787524f11
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.25 16:08:14.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            do_trush(selection);
        });

}

function do_trush( selection)
{
    showInfoPane('*正在移和回收站');
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    resetImageCountInfo();
    hideInfoPane();
}


id: 60d58c32ebaf6f2787524f17
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.25 16:10:40.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            do_trush(selection);
        });

}

function do_trush( selection)
{
    showInfoPane('*正在移和回收站');
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    hideInfoPane();
}


id: 60d58c32ebaf6f2787524f1d
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.25 16:14:54.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            showInfoPane('*正在移和回收站');
            setTimeout(function(){ 
            do_trush(selection);
            hideInfoPane();
            },100);
        });

}

function do_trush( selection)
{
    
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    
}


id: 60d59109ebaf6f2787524fb4
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.145
username: sa
createdate: 2021.06.25 19:07:47.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if( !path.endWith('凭证影像采集目录'))
    {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            showInfoPane('*正在移和回收站');
            setTimeout(function(){ 
            do_trush(selection);
            hideInfoPane();
            },100);
        });

}

function do_trush( selection)
{
    
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    
}


id: 60d5b95cebaf6f2787524fbb
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.145
username: sa
createdate: 2021.06.25 19:09:16.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if( !path.endsWith('凭证影像采集目录'))
    {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            showInfoPane('*正在移和回收站');
            setTimeout(function(){ 
            do_trush(selection);
            hideInfoPane();
            },100);
        });

}

function do_trush( selection)
{
    
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    
}


id: 60d5b95cebaf6f2787524fc6
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.145
username: sa
createdate: 2021.06.25 19:13:44.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit =='')  pathToMonit="c:\\凭证影像采集目录"; 
            moniteStart(pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if( !path.endsWith('凭证影像采集目录'))
    {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            showInfoPane('*正在移和回收站');
            setTimeout(function(){ 
            do_trush(selection);
            hideInfoPane();
            },100);
        });

}

function do_trush( selection)
{
    
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    
}


id: 60d5c0c3ebaf6f278752509f
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.145
username: sa
createdate: 2021.06.25 19:47:41.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);
        getLastPZH(corporationid , ym,  function (v) 
        { if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8); 
        lastPZH = v; });

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit =='')  pathToMonit="c:\\凭证影像采集目录"; 

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：'+pathToMonit);
        }
    }, 500);



    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}

 
// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("【" + book.sheet1.getBrick("imgPool").imageCount + "】张图片");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

 


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }


    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            if (val == '') {

                var p = find_pzh(data.id, false);
                if (p) p.remove();
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
                return true;
            } else {
                if (val.length - pzh_prefix.length != pzh_len) {
                    toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                    return false;

                }
                g_lastPZH = val; //记下来
                find_pzh(data.id, true).find('.no').text(val);
                book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
                return true;
            }

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if( !path.endsWith('凭证影像采集目录'))
    {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick()
{
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn= selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
            showInfoPane('*正在移和回收站');
            setTimeout(function(){ 
            do_trush(selection);
            hideInfoPane();
            },100);
        });

}

function do_trush( selection)
{
    
    for( let i=0;i<  selection.length; i++)
    {
        let one= selection[i];
         moveImageToRecycle(one.id);
        
    }
    cb_refresh_onClick();
    
}


