# app_script_history

id: 637c3ede9932b5d98a4a3c4f
scriptid: 6181e49ac76eefddf45ea05a
tablename: app_script
clientip: 122.235.156.156
username: sa
createdate: 2022.11.22 14:19:49.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
    var watermark = p.watermark; //水印
    var ids = p.ids;
    var gguid = p.gguid;
    var mergePDF = p.mergePDF;

    var topic = "打包下载" + gguid;


    var source = [];
    //封面
    var bf = runTask("createBookFace", { id: gguid });
    println("封面");
    println(bf);
 //   source.push(JSON.parse(bf));

    //针对 每一个凭证，检查一下归档是不是已经生成， 已经生成的，不要重复再生成，没有生成的，那么就先生成它
    for (var i = 0; i < ids.length; i++) {
        println((i + 1) + "  " + ids[i].id);
        var t = "*凭证归档检测。完成" + ((i + 1) * 100.0 / ids.length) + "%";
        println(t);
        pushMessage(topic, { action: "info", info: t }, -1);
        delay(10);

        var t = runTask("pz_image2pdf", {
            id: ids[i].id,
            overwrite: false  //如果已存在，不要重新生成
        });
        println(t);

        if (mergePDF) {
            var pzhfm = runTask("createNo", { pzh:  ids[i].filenameprefix + getStringFromSQL("select pzh from dzpz_pz where id='" + ids[i].id + "'") });

            //每个凭证号加一个小封面
  //          source.push(JSON.parse(pzhfm));
        }

        var oneSource= JSON.parse(t).data;
        oneSource.filenameprefix = ids[i].filenameprefix;  
        source.push( oneSource);
    }


    //source中存放的是每个归档pdf文件的下载地址。在服务器上直接下载，走的是文件服务器下载接口，不是FileServer的http
    // 接口，所以不会自动加上水印
    println(JSON.stringify(source));
    pushMessage(topic, { action: "info", info: "*正在压缩" }, -1);
    var ret = createZipFileTask(p.fileName,
        source,
        watermark,
        500, //每个压缩文件的源文件大小合计不超过 mb 数 
        3,  //放到第3个文件服务器下
        "调阅打包/" + formatDate(newDate(), "yyyy/MM/dd"),//存放子目录
        "后台打包中",
        "后台打包完成",
        "后台打包异常",
        mergePDF, //pdf是否合并 
        {
            table: "dzpz_dy",
            gguid: gguid,

        }
    );


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

}


id: 6401568899321fa4b3b3b7ae
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:15:01.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {



    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    runSQL("", "update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) ");
  						


    runSQL("", ` 
            update pzdjex  
            inner join  dzpz_pz c   on (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) 
            set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  
            ` , true);


    

    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

   runSQL("", `
        update dzpz_pz set pzdj_exist=0 where not exists(
        select
          b.id
        from
          pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);


    runSQL("", `
        update dzpz_pz set pzdj_exist=1 where exists(
        select
          b.id
        from
          pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);

    

}


id: 6401568899321fa4b3b3b7bf
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:21:10.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {



    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    runSQL("", "update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("", ` 
            update pzdjex  
            inner join  dzpz_pz c   on (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) 
            set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  
            ` , true);


    

    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

   runSQL("", `
        update dzpz_pz set pzdj_exist=0 where not exists(
        select
          b.id
        from
          pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);


    runSQL("", `
        update dzpz_pz set pzdj_exist=1 where exists(
        select
          b.id
        from
          pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);

    

}


id: 6401568899321fa4b3b3b7c8
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:21:25.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {



    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    runSQL("", "update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("", ` 
            update pzdjex  
            inner join  dzpz_pz c   on (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) 
            set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  
            ` , true);



    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL("", `
        update dzpz_pz set pzdj_exist=0 where not exists(
        select
          b.id
        from
          pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);


    runSQL("", `
        update dzpz_pz set pzdj_exist=1 where exists(
        select
          b.id
        from
          pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);

    

}


id: 6401568899321fa4b3b3b7d1
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:21:38.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {


    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    runSQL("", "update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("", ` 
            update pzdjex  
            inner join  dzpz_pz c   on (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) 
            set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  
            ` , true);



    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL("", `
        update dzpz_pz set pzdj_exist=0 where not exists(
        select
          b.id
        from
          pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);


    runSQL("", `
        update dzpz_pz set pzdj_exist=1 where exists(
        select
          b.id
        from
          pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh
      )
     ` , true);

    

}


id: 6401568899321fa4b3b3b7dc
scriptid: 617cc6bb99328c3820c0b3a7
tablename: app_template
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:26:32.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    // 追加一些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>
                    `);

//把凭证信息表中的corpid同步一下，2022.10月前，明细中的corpid是null 
     corpid_sync( function(){});

}

/**
 * 单元格单击事件。仅当点击处有一个有效单元格时才触发本事件。当在有效行列之外点击时， 不触发本事件。
 * 当在有效行列之内但该坐标处并没有创建单元格时，也不会触发。
 * 注：当通过row,col定位到一个单元格时，如果在模板设计时并没有对该单元格做任何属性设置，那么此坐标处是空的，并不存在单元格对象，这种情况很少见
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被点击
 * @param event 事件对象
 */
//@comment (group=单元格事件,caption=单元格点击)
function cellOnClick(sheet, cell, innerRow, event) {


    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'q_hz') {
        let sheet_mx = book.getWorkSheet("mx");
        sheet_mx.cells("st_corpid").setValue($q_hz_ds.getString(innerRow, "corpid"));
        let ym = $q_hz_ds.getString(innerRow, "ym");
        sheet_mx.cells("st_y").setValue(ym.substring(0, 4));
        sheet_mx.cells("st_m").setValue(ym.substring(4, 6));
        //book.getWorkSheet("mx").cells("st_corpid").setValue("001");
    }
    let value = cell.getValueDouble(innerRow);
    if (bind != null && bind.dataSource == 'q_hz' && bind.DBCol == 'pzsl_dj_wpic' && value > 0) cell_pzsl_dj_wpic_onClick(sheet, cell, innerRow, event);//未影像化凭证列表
    if (bind != null && bind.dataSource == 'q_hz' && bind.DBCol == 'pzsl_pic_wdj' && value > 0) cell_pzsl_pic_wdj_onClick(sheet, cell, innerRow, event);//未登记凭证列表

}

//@comment (group=,caption=已登记未影像化的凭证列表,needRightControl=false)
function cell_pzsl_dj_wpic_onClick(sheet, cell, innerRow, event) {
    book.getWorkSheet("mx").cells("st_status").setValue(1);
    // book.getWorkSheet("mx").float('fa fa-cog', "凭证列表",
    //     {
    //         my: 'right-center',
    //         at: 'right-center',
    //         autoposition: 'down',
    //         offsetX: -5,
    //         offsetY: 5
    //     }, { width: 700, height: "90%" });
    smartRetrieve(book.getWorkSheet("mx_list"), "q_mx");
    book.setActiveSheet("mx");
}
//@comment (group=,caption=未登记凭证列表,needRightControl=false)
function cell_pzsl_pic_wdj_onClick(sheet, cell, innerRow, event) {
    book.getWorkSheet("mx").cells("st_status").setValue(-1);
    book.setActiveSheet("mx");
    // book.getWorkSheet("mx").float('fa fa-cog', "凭证列表",
    //     {
    //         my: 'right-center',
    //         at: 'right-center',
    //         autoposition: 'down',
    //         offsetX: -5,
    //         offsetY: 5
    //     }, { width: 700, height: "90%" });
    smartRetrieve(book.getWorkSheet("mx_list"), "q_mx");

}

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

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

    }
}


function loadPZ(pzh, id) {
    let data = getPZFJ(id); //得到凭证的所有图片
    let FJ = book.getWorkSheet("mx_img").getBrick('FJ');
    FJ.buildGridly(data, function () {

        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, pzh, false);
            }
        }

    });
    book.getWorkSheet("mx").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;

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_return_onClick(sheet, cell, button) {
    book.setActiveSheet("main");

}


function cb_export1_onClick()
{
    form.export_excel2( book.sheet2);

}

function cb_export2_onClick()
{
    form.export_excel2( book.sheet4);
    
}

function  cb_recalc_onClick()
{

    let y= book.sheet1.cells("st_y").getValueInt();
    let m= book.sheet1.cells("st_m").getValueInt();
    if( y==0 || m==0)
    {
        $.alert("请选择年度和月份后再进行重新核算");
        return;
    }

    $confirm("提示","系统每天自动计算两次。所以统计结果可能会略滞后。可以点击重新核算强行重新计算以保证数据是最新的。",function()
    {
        showInfoPane( "*正在计算...") ;
    runTask("updateForReport",{ y:y, m:m } ,function(ret)
    {
        hideInfoPane();
        toastr.info("核算完成 ，请重新检索");
    })
    });
}


id: 6401568899321fa4b3b3b7f8
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:38:45.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {


    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    var p= JSON.parse(arg);
    var y=0;
    var m=0;
    var ym='';
    if( p.y !=undefined) 
    {
        y=p.y;
        m=p.m;
        ym= ''+ round(  y*100  + m ,0); 
    }
    println("y,m = "+ y+","+m );

    runSQL("", " update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where "+ 
         (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
         +" not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and "+
                (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
                "  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("",  " update pzdjex  " + 
             " inner join  dzpz_pz c   on ( "+
              (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
             " pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) "+
            " set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  " 
            , true);



    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL(""," update dzpz_pz set pzdj_exist=0 where "+
         (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        " not exists(  select  b.id from  pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh  ) "
       , true);


    runSQL("",  "  update dzpz_pz set pzdj_exist=1 where "+
        (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        "  exists(  select   b.id  from  pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh    )"   , true);

    

}


id: 6401568899321fa4b3b3b801
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:41:03.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {


    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID


    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    var p= JSON.parse(arg);
    var y=0;
    var m=0;
    var ym='';
    if( p.y !=undefined) 
    {
        y=p.y;
        m=p.m;
        ym= ''+ round(  y*100  + m ,0); 
    }
    println("y,m = "+ y+","+m );

    runSQL("", " update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where "+ 
         (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
         " not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and "+
                (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
                "  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("",  " update pzdjex  " + 
             " inner join  dzpz_pz c   on ( "+
              (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
             " pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) "+
            " set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  " 
            , true);



    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL(""," update dzpz_pz set pzdj_exist=0 where "+
         (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        " not exists(  select  b.id from  pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh  ) "
       , true);


    runSQL("",  "  update dzpz_pz set pzdj_exist=1 where "+
        (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        "  exists(  select   b.id  from  pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh    )"   , true);

    

}


id: 64015e8799321fa4b3b3b80a
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:42:16.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {


    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID
    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    println("=========================");
    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    var p= JSON.parse(arg);
    var y=0;
    var m=0;
    var ym='';
    if( p.y !=undefined) 
    {
        y=p.y;
        m=p.m;
        ym= ''+ round(  y*100  + m ,0); 
    }
    println("y,m = "+ y+","+m );

    runSQL("", " update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where "+ 
         (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
         " not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and "+
                (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
                "  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("",  " update pzdjex  " + 
             " inner join  dzpz_pz c   on ( "+
              (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
             " pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) "+
            " set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  " 
            , true);



   
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL(""," update dzpz_pz set pzdj_exist=0 where "+
         (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        " not exists(  select  b.id from  pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh  ) "
       , true);


    runSQL("",  "  update dzpz_pz set pzdj_exist=1 where "+
        (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        "  exists(  select   b.id  from  pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh    )"   , true);

    

}


id: 64015e8799321fa4b3b3b813
scriptid: 6371e8229932b5d98a4a2e1b
tablename: app_script
clientip: 122.233.193.104
username: sa
createdate: 2023.03.03 10:44:45.000
script:
/**
 *   导入凭证信息需要更新它有没有被影像化
 * 
 *    影像归档需要更新有没有对应的导入信息 
 *    这里直接更新到各自的字段中，便于统计分析 
 *
 */
function main(arg) {


    runSQL("", " alter table  pzdjex add  pzsl_pic int null ",false);  // 1 表示已经影像化
    runSQL("", " alter table  pzdjex add  pic_pz int null ",false);  // 对应的凭证图片张数
    runSQL("", " alter table  pzdjex add  pic_fj int null ",false);  //对应的附件图片张数
    runSQL("", " alter table  pzdjex add  dzpz_id  varchar(40)  null ",false);  //对应的影像化记录的ID
    runSQL("", "alter table dzpz_pz  add pzdj_exist int null ",false); //  1 表示有对应的导入的凭证信息， 0 表示没有
    println("=========================");
    runSQL("", "update pzdjex  set pic_pz=0 where pic_pz is null ",true);
    runSQL("", "update pzdjex  set pic_fj=0 where pic_fj is null ",true);

    var p= JSON.parse(arg);
    var y=0;
    var m=0;
    var ym='';
    if( p.y !=undefined) 
    {
        y=p.y;
        m=p.m;
        ym= ''+    (y*100  + m) ; 
    }
    println("y,m = "+ y+","+m );

    println("ym = "+ ym );

    runSQL("", " update pzdjex  set    dzpz_id= null,   pic_pz =0  ,   pic_fj= 0 where "+ 
         (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
         " not exists ( select id from  dzpz_pz c   where  (  pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) ) " ,true);
  						
	runSQL("", "update pzdjex  join pzdj on ( pzdjex.corpid is null  and "+
                (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
                "  pzdjex.gguid= pzdj.gguid)   set  pzdjex.corpid = pzdj.corpid ",true);
						 

    runSQL("",  " update pzdjex  " + 
             " inner join  dzpz_pz c   on ( "+
              (( y==0)? "" : "  pzdjex.y ="+y+"  and  pzdjex.m = "+ m+ " and "   ) + 
             " pzdjex.corpid = c.corpid and pzdjex.pzh = c.pzh  ) "+
            " set   pzdjex.dzpz_id= c.id,  pzdjex.pic_pz =1 ,  pzdjex.pic_pz = c.pz , pzdjex.pic_fj= c.fj  " 
            , true);



   
    runSQL("", " update dzpz_pz set pzdj_exist=0  where  	pzdj_exist is null  ",true);

    runSQL(""," update dzpz_pz set pzdj_exist=0 where "+
         (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        " not exists(  select  b.id from  pzdjex b  where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh  ) "
       , true);


    runSQL("",  "  update dzpz_pz set pzdj_exist=1 where "+
        (( y==0)? "" : "  left( dzpz_pz.ym ,4)='"+ ym +"'  and "   ) + 
        "  exists(  select   b.id  from  pzdjex b where   dzpz_pz.corpid = b.corpid  and dzpz_pz.pzh = b.pzh    )"   , true);

    

}


id: 6433db3f99328efdf2682dd6
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 180.169.212.101
username: sa
createdate: 2023.04.19 16:15:05.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0,"corpid");
    
    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "凭证日期": "pzrq",
        "核算账号编码": "code",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人":"jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row,"corpid" , corpid);
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

        //更新起始记账期和截止记账期
        var master_ds = newDataStore(dsn, "select * from " + masterTable);
        master_ds.setUpdateProperty(masterTable, "id", "*", "id");
        master_ds.retrieve("gguid='" + currentGUID() + "'");
        master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.update(true)
    } else {
        ret.message = ds.getError().getMessage();
    }
    pushMessage('dr_info', 'over', currentUserId());

    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: 643fa50599328efdf2682f62
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 180.169.212.101
username: sa
createdate: 2023.04.19 16:29:20.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0,"corpid");
    
    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人":"jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row,"corpid" , corpid);
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

        //更新起始记账期和截止记账期
        var master_ds = newDataStore(dsn, "select * from " + masterTable);
        master_ds.setUpdateProperty(masterTable, "id", "*", "id");
        master_ds.retrieve("gguid='" + currentGUID() + "'");
        master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.update(true)
    } else {
        ret.message = ds.getError().getMessage();
    }
    pushMessage('dr_info', 'over', currentUserId());

    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: 643fa6f399328efdf2682f6a
scriptid: 60d095db993254220bd851a3
tablename: app_template
clientip: 180.169.212.101
username: sa
createdate: 2023.04.19 16:31:48.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    onPushMessage("dr_info", function (info) {
        if (info == 'over') {
            hideInfoPane();
        } else {
            showInfoPane(info);
        };

    })

}

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

    book.readXLS(function (data) {
        // alert(JSON.stringify(data));
        showInfoPane("*正在导入");
        backend_importExcelData(data[Object.keys(data)[0]], function (ret) {
            //console.dir(ret);
            hideInfoPane();
            if (ret.success) {
                toastr.info('导入成功');
                smartRetrieve(book.getWorkSheet("main"), "pzdj");
                smartRetrieve(book.getWorkSheet("detail"), "pzdjex");
                
            } else {
                toastr.warning(ret.message);
            }
        });
    });
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t借方金额\t贷方金额\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人\t经办人";
    var data = [];
    data.push(title);
    data.push("2021\t6\t210600001\t2021.06.01\t5501\t营业费用\t500\t500\t\t\t\t\tY71JY21201\tRK0001\t否\t这是凭证摘要\t张三");


    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证资料导入模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}


id: 6474132b9932720331487412
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.05.29 10:55:32.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 600, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{
    $setClipboard(url);
    toastr.info("下载地址已经复制到剪贴板");
}


id: 6474132b9932720331487418
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.05.29 10:58:19.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 600, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{
    $setClipboard( getServiceHomeURL( 'app')+"/"+ url);
    toastr.info("下载地址已经复制到剪贴板");
}


id: 6474132b993272033148741e
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.05.29 10:58:43.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 600, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{
    $setClipboard( getServiceHomeURL( 'app')+  url);
    toastr.info("下载地址已经复制到剪贴板");
}


id: 6477fb5c9932304b13e82e3d
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.01 10:05:31.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

        book.sheet0.cells("ym").setValue(ym);

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


    });

    book.sheet2.getBrick('FJ').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>
                    `);


}

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 viewPDF( id)
{
    var url=  get_PZ_PDF_URL(id);
    openWindow(url);
}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'ym') {
        var corpid = book.sheet0.cells("corpid").getValueString();
        var ym = book.sheet0.cells("ym").getValue();

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




}

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);
            }
        }




    });
    g_selectedAll = 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 , function(){ book.getDataSource('dzpz_pz').currntBindRow= innerRow +1  } );
        }
        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 rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在审核确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在审核确认 " + i  );
                do_sh1(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("审核完成");
        });

    });
}



function cb_unverify_onClick() {

    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {
        var rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在取消确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在取消确认"+i);
                do_sh2(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("取消确认完成");
        });

    });


}


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);
                }
            });

    });
}

function isVerified() {
    var row = book.getDataSource('dzpz_pz').currentBindRow;
    var verifiername = $dzpz_pz_ds.getString(row, "verifiername");

    if (verifiername != '') {
        toastr.error("已经校对的凭证不允许执行此操作");
        return true;
    }
    return false;
}


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


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

        brick.addToolButton(1  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '90' ,function(){hideInfoPane();});

            }
        );


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

            }
        );


        brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-rotate-left",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '270',function(){hideInfoPane();});

            }
        );



    }
}


function rotateImg(sheet, id, degree, callback) {



    let brick = sheet.getBrick('FJ');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID

        do_imageRotate(id, degree, function (ret) {


            if (ret.success) {

                g_turningCount++;
                showInfoPane('*正在旋转图片' + g_turningCount + "/" + g_turnNeedCount + ' ...');


                //把数据中的图片替换，
                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);

            }
            if (callback) callback();



        });
    }, 100);

}


/**
 * 图片控件中的图片控件顺序发生变化
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *@param  ids  当前顺序下的图片的ID数组
 *
 *
 *
 */
//@comment (group=图片控件,caption=图片顺序被改变)
function imageOrderChanged(sheet, name, ids) {

    if (isVerified()) return;  //校对过的不允许再调整顺序

    reOrderImage(ids, function (ret) { }); //放一个空的回调函数让它异步执行，不卡界面

}


var g_selectedAll = false;
function cb_selectallimg_onClick() { g_selectedAll = !g_selectedAll; doSelect(g_selectedAll); }


function doSelect(b) {
    var imgPool = book.sheet2.getBrick('FJ');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_turnLeft_onClick() {
    turnSelection('270');

}

function cb_turnRight_onClick() {

    turnSelection('90');
}

var g_turningCount = 0;
var g_turnedCount = 0;

function turnSelection(degree) {

    if (isVerified()) return;  //校对过的不允许再旋转

    var sheet = book.sheet2;
    var imgPool = sheet.getBrick('FJ');
    // 当前选中的
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }


    $confirm("提示", "确信要对选中的" + selection.length + "张图片做旋转吗?", function () {

        g_turningCount = 0;
        g_turnedCount = 0;
        g_turnNeedCount = selection.length;
        /*
                setTimeout(function () {
                    for (var i = 0; i < selection.length; i++) {
                        rotateImg(sheet, selection[i].id, degree, i * 1000);
                    }
                }, 10);
                */

        asyncPool(4 , selection, function (item, array) {
            return new Promise(function (resolve, reject) {

                console.dir(item);
                rotateImg(sheet, item.id, degree,
                    function () { //注意，在旋转完成后，再设置resolve 表示本任务已完成，而不是直接就resolve ,不然最后的 then 执行时机不对，这么处理，就会在全部旋转完成后，再执行then中的脚本，而不是旋转任务全部发起后就执行 then 
                        resolve(item)
                    });

            });
        }).then(function () {

            setTimeout(function () {

                hideInfoPane();
                toastr.info("旋转完成");
            }, 500);
        });

    });

}


 

function test1() {


    asyncPool(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function (item, array) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.info(item + "   "+ new Date());
                resolve(item)
            }, 1000);

        });
    }).then(function () {
        console.info("over");
    });

}


id: 6477fb5c9932304b13e82e43
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.01 10:06:05.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

        book.sheet0.cells("ym").setValue(ym);

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


    });

    book.sheet2.getBrick('FJ').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>
                    `);


}

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 viewPDF(id) {
    var url = get_PZ_PDF_URL(id);
    openWindow(url);
}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'ym') {
        var corpid = book.sheet0.cells("corpid").getValueString();
        var ym = book.sheet0.cells("ym").getValue();

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




}

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);
            }
        }




    });
    g_selectedAll = 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, function () {
                if (innerRow < $dzpz_pz_ds.rowCount - 1) {
                    book.getDataSource('dzpz_pz').currntBindRow = innerRow + 1
                }
            });
        }
        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 rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在审核确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在审核确认 " + i);
                do_sh1(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("审核完成");
        });

    });
}



function cb_unverify_onClick() {

    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {
        var rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在取消确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在取消确认" + i);
                do_sh2(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("取消确认完成");
        });

    });


}


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);
                }
            });

    });
}

function isVerified() {
    var row = book.getDataSource('dzpz_pz').currentBindRow;
    var verifiername = $dzpz_pz_ds.getString(row, "verifiername");

    if (verifiername != '') {
        toastr.error("已经校对的凭证不允许执行此操作");
        return true;
    }
    return false;
}


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


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

        brick.addToolButton(1  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '90', function () { hideInfoPane(); });

            }
        );


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

            }
        );


        brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-rotate-left",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '270', function () { hideInfoPane(); });

            }
        );



    }
}


function rotateImg(sheet, id, degree, callback) {



    let brick = sheet.getBrick('FJ');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID

        do_imageRotate(id, degree, function (ret) {


            if (ret.success) {

                g_turningCount++;
                showInfoPane('*正在旋转图片' + g_turningCount + "/" + g_turnNeedCount + ' ...');


                //把数据中的图片替换，
                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);

            }
            if (callback) callback();



        });
    }, 100);

}


/**
 * 图片控件中的图片控件顺序发生变化
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *@param  ids  当前顺序下的图片的ID数组
 *
 *
 *
 */
//@comment (group=图片控件,caption=图片顺序被改变)
function imageOrderChanged(sheet, name, ids) {

    if (isVerified()) return;  //校对过的不允许再调整顺序

    reOrderImage(ids, function (ret) { }); //放一个空的回调函数让它异步执行，不卡界面

}


var g_selectedAll = false;
function cb_selectallimg_onClick() { g_selectedAll = !g_selectedAll; doSelect(g_selectedAll); }


function doSelect(b) {
    var imgPool = book.sheet2.getBrick('FJ');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_turnLeft_onClick() {
    turnSelection('270');

}

function cb_turnRight_onClick() {

    turnSelection('90');
}

var g_turningCount = 0;
var g_turnedCount = 0;

function turnSelection(degree) {

    if (isVerified()) return;  //校对过的不允许再旋转

    var sheet = book.sheet2;
    var imgPool = sheet.getBrick('FJ');
    // 当前选中的
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }


    $confirm("提示", "确信要对选中的" + selection.length + "张图片做旋转吗?", function () {

        g_turningCount = 0;
        g_turnedCount = 0;
        g_turnNeedCount = selection.length;
        /*
                setTimeout(function () {
                    for (var i = 0; i < selection.length; i++) {
                        rotateImg(sheet, selection[i].id, degree, i * 1000);
                    }
                }, 10);
                */

        asyncPool(4, selection, function (item, array) {
            return new Promise(function (resolve, reject) {

                console.dir(item);
                rotateImg(sheet, item.id, degree,
                    function () { //注意，在旋转完成后，再设置resolve 表示本任务已完成，而不是直接就resolve ,不然最后的 then 执行时机不对，这么处理，就会在全部旋转完成后，再执行then中的脚本，而不是旋转任务全部发起后就执行 then 
                        resolve(item)
                    });

            });
        }).then(function () {

            setTimeout(function () {

                hideInfoPane();
                toastr.info("旋转完成");
            }, 500);
        });

    });

}




function test1() {


    asyncPool(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function (item, array) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.info(item + "   " + new Date());
                resolve(item)
            }, 1000);

        });
    }).then(function () {
        console.info("over");
    });

}


id: 6477fb5c9932304b13e82e49
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.01 10:07:40.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

        book.sheet0.cells("ym").setValue(ym);

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


    });

    book.sheet2.getBrick('FJ').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>
                    `);


}

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 viewPDF(id) {
    var url = get_PZ_PDF_URL(id);
    openWindow(url);
}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'ym') {
        var corpid = book.sheet0.cells("corpid").getValueString();
        var ym = book.sheet0.cells("ym").getValue();

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




}

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);
            }
        }




    });
    g_selectedAll = 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, function () {
                if (innerRow < $dzpz_pz_ds.rowCount - 1) {
                    book.getDataSource('dzpz_pz').currentBindRow = innerRow + 1 ;
                }
            });
        }
        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 rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在审核确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在审核确认 " + i);
                do_sh1(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("审核完成");
        });

    });
}



function cb_unverify_onClick() {

    $confirm('', '确信要对选中的凭证做取消审核吗?', function () {
        var rows = [];
        for (let i = 0; i < $dzpz_pz_ds.rowCount; i++) {
            if ($dzpz_pz_ds.getInt(i, "selected") == 0) continue;
            rows.push(i);
        };

        showInfoPane("* 正在取消确认...");
        asyncPool(4, rows, function (i, rows) {
            return new Promise(function (resolve, reject) {
                showInfoPane("* 正在取消确认" + i);
                do_sh2(i, function () {
                    resolve(i);
                });
            });
        }).then(function (v) {
            hideInfoPane();
            toastr.info("取消确认完成");
        });

    });


}


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);
                }
            });

    });
}

function isVerified() {
    var row = book.getDataSource('dzpz_pz').currentBindRow;
    var verifiername = $dzpz_pz_ds.getString(row, "verifiername");

    if (verifiername != '') {
        toastr.error("已经校对的凭证不允许执行此操作");
        return true;
    }
    return false;
}


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


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

        brick.addToolButton(1  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '90', function () { hideInfoPane(); });

            }
        );


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

            }
        );


        brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-rotate-left",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数
                g_turningCount = 0;
                g_turnedCount = 0;
                g_turnNeedCount = 1;
                if (isVerified()) return;  //校对过的不允许再旋转

                rotateImg(sheet, id, '270', function () { hideInfoPane(); });

            }
        );



    }
}


function rotateImg(sheet, id, degree, callback) {



    let brick = sheet.getBrick('FJ');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID

        do_imageRotate(id, degree, function (ret) {


            if (ret.success) {

                g_turningCount++;
                showInfoPane('*正在旋转图片' + g_turningCount + "/" + g_turnNeedCount + ' ...');


                //把数据中的图片替换，
                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);

            }
            if (callback) callback();



        });
    }, 100);

}


/**
 * 图片控件中的图片控件顺序发生变化
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *@param  ids  当前顺序下的图片的ID数组
 *
 *
 *
 */
//@comment (group=图片控件,caption=图片顺序被改变)
function imageOrderChanged(sheet, name, ids) {

    if (isVerified()) return;  //校对过的不允许再调整顺序

    reOrderImage(ids, function (ret) { }); //放一个空的回调函数让它异步执行，不卡界面

}


var g_selectedAll = false;
function cb_selectallimg_onClick() { g_selectedAll = !g_selectedAll; doSelect(g_selectedAll); }


function doSelect(b) {
    var imgPool = book.sheet2.getBrick('FJ');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_turnLeft_onClick() {
    turnSelection('270');

}

function cb_turnRight_onClick() {

    turnSelection('90');
}

var g_turningCount = 0;
var g_turnedCount = 0;

function turnSelection(degree) {

    if (isVerified()) return;  //校对过的不允许再旋转

    var sheet = book.sheet2;
    var imgPool = sheet.getBrick('FJ');
    // 当前选中的
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }


    $confirm("提示", "确信要对选中的" + selection.length + "张图片做旋转吗?", function () {

        g_turningCount = 0;
        g_turnedCount = 0;
        g_turnNeedCount = selection.length;
        /*
                setTimeout(function () {
                    for (var i = 0; i < selection.length; i++) {
                        rotateImg(sheet, selection[i].id, degree, i * 1000);
                    }
                }, 10);
                */

        asyncPool(4, selection, function (item, array) {
            return new Promise(function (resolve, reject) {

                console.dir(item);
                rotateImg(sheet, item.id, degree,
                    function () { //注意，在旋转完成后，再设置resolve 表示本任务已完成，而不是直接就resolve ,不然最后的 then 执行时机不对，这么处理，就会在全部旋转完成后，再执行then中的脚本，而不是旋转任务全部发起后就执行 then 
                        resolve(item)
                    });

            });
        }).then(function () {

            setTimeout(function () {

                hideInfoPane();
                toastr.info("旋转完成");
            }, 500);
        });

    });

}




function test1() {


    asyncPool(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function (item, array) {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.info(item + "   " + new Date());
                resolve(item)
            }, 1000);

        });
    }).then(function () {
        console.info("over");
    });

}


id: 64986f1299328c1024d65703
scriptid: 6181e49ac76eefddf45ea05a
tablename: app_script
clientip: 115.199.153.90
username: sa
createdate: 2023.06.26 00:46:43.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
    var watermark = p.watermark; //水印
    var ids = p.ids;
    var gguid = p.gguid;
    var mergePDF = p.mergePDF;

    var topic = "打包下载" + gguid;


    var source = [];
    //封面
   // var bf = runTask("createBookFace", { id: gguid });
   // println("封面");
   // println(bf);
 //   source.push(JSON.parse(bf));

    //针对 每一个凭证，检查一下归档是不是已经生成， 已经生成的，不要重复再生成，没有生成的，那么就先生成它
    for (var i = 0; i < ids.length; i++) {
        println((i + 1) + "  " + ids[i].id);
        var t = "*凭证归档检测。完成" + ((i + 1) * 100.0 / ids.length) + "%";
        println(t);
        pushMessage(topic, { action: "info", info: t }, -1);
        delay(10);

        var t = runTask("pz_image2pdf", {
            id: ids[i].id,
            overwrite: false  //如果已存在，不要重新生成
        });
        println(t);

        if (mergePDF) {
            var pzhfm = runTask("createNo", { pzh:  ids[i].filenameprefix + getStringFromSQL("select pzh from dzpz_pz where id='" + ids[i].id + "'") });

            //每个凭证号加一个小封面
  //          source.push(JSON.parse(pzhfm));
        }

        var oneSource= JSON.parse(t).data;
        oneSource.filenameprefix = ids[i].filenameprefix;  
        source.push( oneSource);
    }


    //source中存放的是每个归档pdf文件的下载地址。在服务器上直接下载，走的是文件服务器下载接口，不是FileServer的http
    // 接口，所以不会自动加上水印
    println(JSON.stringify(source));
    pushMessage(topic, { action: "info", info: "*正在压缩" }, -1);
    var ret = createZipFileTask(p.fileName,
        source,
        watermark,
        500, //每个压缩文件的源文件大小合计不超过 mb 数 
        3,  //放到第3个文件服务器下
        "调阅打包/" + formatDate(newDate(), "yyyy/MM/dd"),//存放子目录
        "后台打包中",
        "后台打包完成",
        "后台打包异常",
        mergePDF, //pdf是否合并 
        {
            table: "dzpz_dy",
            gguid: gguid,

        }
    );


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

}


id: 6498e5ad9932f8e5e3987a54
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.26 10:50:07.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 800, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{

    let t= getServiceHomeURL( 'app')+  url;

    toastr.info("下载地址已经复制到剪贴板");
}


id: 6498fd569932f8e5e3987a80
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.26 10:53:27.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);

    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ids = [];
    //2022.08.11 优化， 有可能存在重复的，所能加上 distinct 去重
    var $dzpz_dymx_ds = newDataStore("", "select  pz_id ,pzh , max(filenameprefix) as filenameprefix from  dzpz_dymx where gguid='" + gguid + "' group by pz_id, pzh  order by pzh  ");
    $dzpz_dymx_ds.retrieve();
    println($dzpz_dymx_ds.getSelectLastRetrieved());

    for (var i = 0; i < $dzpz_dymx_ds.getRowCount(); i++) {
        var pz_id = '' + $dzpz_dymx_ds.getString(i, "pz_id");
        var filenameprefix = $dzpz_dymx_ds.getString(i, "filenameprefix");
        if (pz_id == '') continue;
        if (ids.contains(pz_id)) continue;
        ids.push({ id:pz_id , filenameprefix: filenameprefix} );
    }

    if (ids.length == 0) {
        println("没有凭证清单");
        return;
    }

    println(ids.length + "张凭证需要打包");

    var $dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy where gguid='" + gguid + "'");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    $dzpz_dy_ds.retrieve();

    var fileName = $dzpz_dy_ds.getString(0, "reader") + formatDate(newDate(), "yyyy.MM.dd") + "因"+$dzpz_dy_ds.getString(0, "summary") + "调阅凭证.zip";

    var ret = runTask("后台打包", {
        gguid: gguid,
        fileName: fileName,
        ids: ids,
        watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : (formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
        mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件

    });

    println(ret);
    ret = JSON.parse(ret);

    if (ret.success) {
        $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
        $dzpz_dy_ds.update(true);
    }
    return ret;
}



function back_urlShare(url , d , t)
{
    var ret= urlShare( url , d, "day", t);
    return ret.url;  
}


id: 6498fd569932f8e5e3987a89
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.26 10:55:31.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 800, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{

    let t= getServiceHomeURL( 'app')+  url;
    let d= book.sheet3.cells("days").getValueInt();
    let t =book.sheet3.cells("times").getValueInt();
     t=  back_urlShare(url, d , t);
     $setClipboard( t); 
    toastr.info("分享地址已经复制到剪贴板");
}


id: 6498fd569932f8e5e3987a8f
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 39.170.92.207
username: sa
createdate: 2023.06.26 10:57:06.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人





/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
    book.getWorkSheet('下载清单').visible = false;



    if ($dzpz_dy_ds.getString(0, "ziptaskid") == '') {
        book.sheet1.getBrick('cb_cancel').visible = false;
    }

    if (currentUserId() == $dzpz_dy_ds.getInt(0, "userid")) {
        g_currentUserIsOwner = true;
    }
    //按gguid分开接收消息，避免多个打包的消息混在一起
    onPushMessage("打包下载" + currentGUID(), function (info) {
        console.info(info);
        var msg = JSON.parse(info);
        if (msg.action == 'info') {
            console.info(msg.info);
            if (g_currentUserIsOwner) showInfoPane(msg.info);
        }

        if (msg.action == 'gameOver') {
            var result = msg.result;
            //$.alert(JSON.stringify(result));


            $dzpz_dy_ds.setValue(0, "ziptaskid", '', false);//清除打包任务id，因为已经ok了，但不要触发保存
            //不需要保存 ，因为打包完成脚本中已经回填了，仅在界面上回填一下， 方便显示下载清单
            $dzpz_dy_ds.setValue(0, "zipresult", JSON.stringify(result.zipFiles), false);

            console.dir(result);

            cb_package_onClick();

            hideInfoPane();
        }
        if (msg.action == 'over') {

            hideInfoPane();
        }

        if (msg.action == 'error') {
            $.alert(msg.info);
            hideInfoPane();
        }
    })

    $('.navbar-fixed-top').css("z-index", 1);

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=下载模板,needRightControl=false)
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号\t科目代码\t核算账号编号\t摘要";
    var data = [];
    data.push(title);
    data.push("1\t0001\t1001\tRD0001\tABC");
    data.push("2\t0002\t5501\tRD0002\tBBB");

    var f = $('#form_toexcel')[0];
    f.filename.value = "凭证调阅模板.xlsx";
    f.data.value = JSON.stringify(data);
    f.submit();

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=导入模板,needRightControl=false)
function cb_importFromExcelFile_onClick(sheet, cell, button) {
    toastr.info("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });

}



function safeValue(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];

}

//@comment (group=,caption=从Excel导入数据,needRightControl=false)
function importData(excelData) {
    var excelSheet = excelData[Object.keys(excelData)[0]];


    var headRow = 0; //题头在第几行
    var dataStartRow = 1;// 数据行从第几行开始

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let data = {
            pzh: safeValue(excelSheet, row, 1) || '',
            kmdm: safeValue(excelSheet, row, 2) || '',
            code: safeValue(excelSheet, row, 3) || '',
            memo: safeValue(excelSheet, row, 4) || '',
        }
        //alert(JSON.stringify(data));
        if (data.pzh == '') continue;
        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, data);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {


        book.sheet0.paintPermit = false;
        toastr.info("导入完成");

    });
}




var dymx_changed = false;
/**
 * dsname结果集保存前，对row进行数据校验 ，
 * @param dsname 结果集名称
 * @param row  第row行
 * @returns {boolean} true表示检验通过， false表示校验不通过，update被终止
 */
function validate(dsname, row) {
    if (dsname == 'dzpz_dymx') dymx_changed = true;
    return true;
}

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

}



/**
 * 单据保存成功后执行本事件。如果单据不需要保存，或保存失败，则不执行本事件
 * @param GUID 当前单据的GGUID
 * @param action 当前单据正在进行的动作，比如 edit , view
 */
function afterSaveSuccessful(GGUID, action) {
    if (dymx_changed) form.loadBill(GGUID); //如果明细有变化，那么保存成功后，重新加载单据，因为在单据保存后，模板后端脚本中会同时更新  pz_id 及 bz
    dymx_changed = false;
}


//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_redo_pack_onClick() {

    $confirm('', '确信要清除压缩文件吗?', function () {

        book.getWorkSheet('下载清单').popupDispose( ) ; 
        
        setTimeout(function () {
            showInfoPane("*正在删除已打包的文件");
            setTimeout(function () {
                $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                $dzpz_dy_ds.setValue(0, "zipresult", '');
                form.save(false);
                $q_result_ds.reset();
                hideInfoPane();
                toastr.info("打包文件已经删除。当再次点击打包下载时会重新打包");
            }, 200);
        },1000);
    });


}

//@comment (group=按钮点击事件,caption=取消打包,needRightControl=false)
function cb_cancel_onClick() {

    $confirm('', '确信要终止打包吗?', function () {
        showInfoPane("*正在终止打包...");
        runTask("终止打包", {
            id: $dzpz_dy_ds.getString(0, "ziptaskid")
        },
            function (ret) {
                ret = JSON.parse(ret);
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", '');
                    $dzpz_dy_ds.setValue(0, "zipresult", '');

                    form.save(false);
                    hideInfoPane();
                } else {
                    toastr.error(ret.message);
                }
            });

    });
}

//@comment (group=按钮点击事件,caption=打包,needRightControl=false)
function cb_package_onClick() {

    form.save(false, function () {
        var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
        if (ziptaskid != '') {
            toastr.info("正在压缩中...，请稍候");
            return;
        }

        var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
        if (zipResult == '') {
            toastr.info("正在压缩文件，请稍候");
            do_package(currentGUID(), function (ret) {

                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId, false); //后台已经回写了，就里只要界面上更新就ok
                }
            });
            return;
        }

        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
        $q_result_ds.reset();
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var row = $q_result_ds.insertRow(999);
            $q_result_ds.setValue(row, one);


        }

        book.getWorkSheet('下载清单').popup("", "下载清单", 800, 300, true, true);
    });
}



function cb_package_onClick___() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要打包下载吗?', function () {
        showInfoPane("*正在压缩打包...");
        let fileName = formatDate(newDate(), "yyyyMMddHHmm") + ".zip";
        runTask("打包下载", {
            fileName: fileName,
            gguid: currentGUID(),
            ids: ids,
            watermark: $dzpz_dy_ds.getString(0, "billno") + "[" + $dzpz_dy_ds.getString(0, "reader") + "]" +
                formatDate(newDate(), "yyyy.MM.dd HH:mm")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    let t = window.location.href;
                    let p = t.indexOf("billedit");
                    t = t.substring(0, p);
                    let url = t + ret.url;
                    $.alert(` <a href="${url}" target="_blank">点击下载${fileName}</a>`, `打包完成`);
                } else {
                    toastr.error(ret.message);
                }
            });

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=调取凭证列表,needRightControl=false)
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.getWorkSheet("凭证资料查询").float('fa fa-cog', "凭证资料查询",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '70%', height: '90%' });
    smartRetrieve(book.getWorkSheet("凭证资料查询"), "q_pzdjex")
}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=选入,needRightControl=false)
function cb_import_onClick(sheet, cell, button) {
    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;

    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);
            $dzpz_dymx_ds.setValue(row, {
                pzh: $q_pzdjex_ds.getValue(i, "pzh"),
                kmdm: $q_pzdjex_ds.getValue(i, "kmdm"),
                code: $q_pzdjex_ds.getValue(i, "code"),
                memo: $q_pzdjex_ds.getString(i, "bz")
            });
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项

    //********删除行号***********************************
    book.getWorkSheet("凭证资料查询").paintPermit = false;
    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
    book.getWorkSheet("凭证资料查询").paintPermit = true;
    //**************************************************

    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=,needRightControl=false)
function cb_opensheet_dr_onClick(sheet, cell, button) {
    book.getWorkSheet("凭证列表").float('fa fa-cog', "导入凭证列表",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: 400, height: '80%' });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=粘贴界面导入,needRightControl=false)
function cb_dr_onClick(sheet, cell, button) {

    book.getWorkSheet("detail").paintPermit = false;
    let row = book.getDataSource("dzpz_dymx").currentBindRow;
    let pzlist = sheet.cells('pzlist').getValueString().split('\n');
    for (let i = 0; i < pzlist.length; i++) {
        if (pzlist[i] !== '') {
            if ($dzpz_dymx_ds.getString(row, "pzh") != '' || row < 0) row = $dzpz_dymx_ds.insertRow(row + 1);

            $dzpz_dymx_ds.setValue(row, {
                pzh: pzlist[i]
            });
        }
    }
    sheet.cells('pzlist').setValue(null);
    sheet.floatPanelClose();

    book.getWorkSheet("detail").paintPermit = true;

}
/**
 * 单元格因为被编辑而改变。当用户通过编辑单元的值而让单元格发生值改变时本事件被触发。
 * 注意，当使用脚本 sheet.cells(row,col).setValue ( value) 来改变单元格的值时，本事件并不触发
 * @param sheet
 * @param cell
 * @param newValue
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChangedByEdit(sheet, cell, newValue, innerRow) {

    //通过数据库绑定情况来判断

    //通过别名来判断
    if (sheet.name == 'detail' && cell.alias == 'st_selectAll') {
        let ds = $dzpz_dymx_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }
    if (sheet.name == '凭证资料查询' && cell.alias == 'st_selectAll') {
        let ds = $q_pzdjex_ds;
        sheet.paintPermit = false;
        for (var i = 0; i < ds.getRowCount(); i++) {
            ds.setValue(i, "selected", newValue);
        }
        sheet.paintPermit = true;
    }

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】仅用于项目专项审计或检查' 
        })
    }



}

/**
 * 单元格编辑时粘贴内容后触发此事件。
 * @param sheet
 * @param cell
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行被粘贴了内容
 * @param text 当前单元格编辑框中的内容，并不一定是粘贴的内容，是单元格编辑框中原有的内容加上粘贴的内容
 */
//@comment (group=单元格事件,caption=单元格粘贴内容)
function cellOnPaste(sheet, cell, innerRow, text) {

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

    }

    //通过数据库绑定情况来判断
    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        sheet.View.forceCurrentEditControlGiveUpFocus();
    }

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {

    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







//@comment (group=,caption=异步打包,needRightControl=false)
function async_package() {

    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }

    let ids = [];
    for (let i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        if ($dzpz_dymx_ds.getString(i, "pz_id") == '') {
            toastr.error("第" + (i + 1) + "行的凭证号不存在，请核对");
            return;
        }
        ids.push($dzpz_dymx_ds.getString(i, "pz_id"));
    }

    if (ids.length == 0) {
        toastr.info("没有凭证清单");
        return;
    }

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : ($dzpz_dy_ds.getString(0, "reader") + "/" + formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
            mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

                } else {
                    toastr.error(ret.message);
                }
            });

    });


}

//@comment (group=按钮点击事件,caption=标记重复,needRightControl=false)
function cb_qc_onClick() {
    showInfoPane("*正在检测重复的凭证");
    var map = {};
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzh == '') continue;
        if (map[pzh] == undefined) map[pzh] = []; //每个凭证号映射到一个数组，记录它所在的行号
        map[pzh].push(i); // 记录下凭证号对应的行号

    }

    book.getWorkSheet('detail').paintPermit = false;
    for (pzh in map) {
        var rows = map[pzh];
        $dzpz_dymx_ds.setValue(rows[0], "bz", "");
        for (var i = 1; i < rows.length; i++) {
            $dzpz_dymx_ds.setValue(rows[i], "bz", "与第" + (rows[0] + 1) + "行重复");
        }
    }
    book.getWorkSheet('detail').paintPermit = true;
    hideInfoPane();
}

//@comment (group=按钮点击事件,caption=删除重复的,needRightControl=false)
function cb_removeDuplicated_onClick() {

    $confirm('', '确信要清除重复的凭证号吗?', function () {

        do_removeDuplicated()

    });

}


//@comment (group=do,caption=执行删除重复的,needRightControl=false)
function do_removeDuplicated() {

    showInfoPane("*正在删除重复的凭证");
    book.getWorkSheet('detail').paintPermit = false;
    var pzhs = []; //凭证号清单
    var rows = [];// 需要删除的行号
    for (var i = 0; i < $dzpz_dymx_ds.rowCount; i++) {
        var pzh = $dzpz_dymx_ds.getString(i, "pzh");
        if (pzhs.contains(pzh)) //此凭证号此前已经出现过
        {
            rows.push(i);//  需要删除
        } else {
            pzhs.push(pzh); //没有出现过，那么加它到凭证号清单中
        }
    }
    //现在反着删除
    for (var i = rows.length - 1; i >= 0; i--) {
        $dzpz_dymx_ds.deleteRow(rows[i]);
    }
    //form.save(false);
    book.getWorkSheet('detail').paintPermit = false;
    hideInfoPane();
}



/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=按钮点击事件,caption=批量删除已选中记录,needRightControl=false)
function cb_selectedRow_delete_onClick(sheet, cell, button) {
    $confirm("提示", "确定要删除选中的记录吗?", function () {
        book.getWorkSheet('detail').paintPermit = false;
        for (let i = $dzpz_dymx_ds.getRowCount() - 1; i >= 0; i--) {
            if ($dzpz_dymx_ds.getInt(i, "selected") == 1) $dzpz_dymx_ds.deleteRow(i);
        }
        if ($dzpz_dymx_ds.getRowCount() == 0) $dzpz_dymx_ds.insertRow(0);
        book.getWorkSheet('detail').cells("st_selectAll").setValue(0);
        book.getWorkSheet('detail').paintPermit = true;
    }, function () { });



}

function copyURL(url)
{

    url = getServiceHomeURL( 'app')+  url;
    let d= book.sheet3.cells("days").getValueInt();
    let t =book.sheet3.cells("times").getValueInt();
     t=  back_urlShare(url, d , t);
     $setClipboard( t); 
    toastr.info("分享地址已经复制到剪贴板");
}


id: 649a8b9199329f5ca7253b1a
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 15:31:53.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0,"corpid");
    
    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人":"jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row,"corpid" , corpid);
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

        //更新起始记账期和截止记账期
        var master_ds = newDataStore(dsn, "select * from " + masterTable);
        master_ds.setUpdateProperty(masterTable, "id", "*", "id");
        master_ds.retrieve("gguid='" + currentGUID() + "'");
        master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.update(true)
    } else {
        ret.message = ds.getError().getMessage();
    }
    pushMessage('dr_info', 'over', currentUserId());

    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: 649a906999329f5ca7253b4f
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 15:35:35.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0,"corpid");
    
    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人":"jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row,"corpid" , corpid);

        if( ds.getRowCount()==1000) 
        {
            ds.update(true);
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

        //更新起始记账期和截止记账期
        var master_ds = newDataStore(dsn, "select * from " + masterTable);
        master_ds.setUpdateProperty(masterTable, "id", "*", "id");
        master_ds.retrieve("gguid='" + currentGUID() + "'");
        master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
        master_ds.update(true)
     
    pushMessage('dr_info', 'over', currentUserId());

    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: 649a906999329f5ca7253b58
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 15:36:13.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            ds.update(true);
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649a919899329f5ca7253bce
scriptid: 649a906999329f5ca7253b6b
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 16:06:47.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);


    var ktbh = param.ktbh || '';

    if (!param.pzh) return { success: false, message: '没有提供凭证号' };

    var tmpTableName = "t_" + newGUID();
    runSQL("", `drop table  ${tmpTableName}`);
    runSQL("", `create table  ${tmpTableName} ( pzh varchar(40) not null , primary key(pzh)) `);


    for (var i = 0; i < param.pzh.length; i++) {
        var pzh = param.pzh[i];
        runSQL("", `insert into  ${tmpTableName}  ( pzh)  values  ('${pzh}') `);
    }

    try {
        var ds = newDataStore("", `select pzh from ${tmpTableName} a  where not exists ( select b.pzh from pzdjex b  where b.pzh = a.pzh and b.code='${ktbh}') `);
        ds.retrieve();
        if (ds.getRowCount() == 0) {
            ds = newDataStore("", `select pzh from ${tmpTableName} a  where not exists ( select b.pzh from  dzpz_pz b  where b.pzh = a.pzh  ) `);
            ds.retrieve();
            if (ds.getRowCount() == 0) {
                return { success: true, code:'0', messager: `所有凭证号合法，且已影像化` };
            } else {
                var pzhs = [];
                for (var i = 0; i < ds.getRowCount(); i++) {
                    pzhs.push(ds.getString(i, "pzh"));
                }
                runSQL("", `drop table  ${tmpTableName}`);
                return { success: false, code:'1', message: `凭证号合法，但系统中不存在如下凭证的影像资料：${pzhs.join(',')}` };

            }
        }


        var pzhs = [];
        for (var i = 0; i < ds.getRowCount(); i++) {
            pzhs.push(ds.getString(i, "pzh"));
        }
        runSQL("", `drop table  ${tmpTableName}`);
        return { success: false, code:'2'  , message: `系统中不存在课题号为 ${ktbh} 的凭证：${pzhs.join(',')}` };


    }
    catch (err) {

    } finally {
        runSQL("", `drop table  ${tmpTableName}`);
    }


}


id: 649aae2299329f5ca7253cfc
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 17:39:57.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg)
{
    println( arg);
    var param= JSON.parse(arg);
    var gguid= newGUID();
    var username= "sa"; 
    var userid= getUserIdByName( username) ;
    var billno= newBillNo('',  'dzpz_dy',   'billno' ,  '{11111111}' , 'billdate',  newDate(), "" ) ;
    var dzpz_dy_ds =newDataStore("","select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy","id","*","id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, { id:gguid, gguid:gguid, userid: userid , username: username, billdate:newDate() , billno:billno , 
                           reader: param.dyr , summary:param.dyyy , corpid:'00' , 
                           needwatermark:0 ,//不打水印 
                           filetype:'zip' , // 
                           email:param.email ,
                           moredata: JSON.stringify( param.callback_param)
                           });

                          

    var config={ moduleid:'dy' ,//凭证调阅模块代码或ID,
            gguid:gguid,
            flow:'dy', //工作流的代码或ID
            userid: userid, //发起人ID
            subject: `${param.dyr ||''}因 [${param.dyyy ||''}] 调阅凭证`


    };

    newWork( config ) ;

}


id: 649ab17599329f5ca7253d1d
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 17:52:55.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg)
{
    println( arg);
    var param= JSON.parse(arg);
    var gguid= newGUID();
    var moduleid='dy';//模块ID
    var username= "sa"; 
    var userid= getUserIdByName( username) ;
    var billno= newBillNo('',  'dzpz_dy',   'billno' ,  '{11111111}' , 'billdate',  newDate(), "" ) ;
    var dzpz_dy_ds =newDataStore("","select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy","id","*","id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, { id:gguid, gguid:gguid, userid: userid , username: username, billdate:newDate() , billno:billno , 
                           reader: param.dyr , summary:param.dyyy , corpid:'00' , 
                           needwatermark:0 ,//不打水印 
                           filetype:'zip' , // 
                           email:param.email ,
                           moredata: JSON.stringify( param.callback_param)
                           });

    var dzpz_dymx_ds= newDtaStore("","select 8 from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx','id','*',"id");
    var pzh = param.pzh|| [];
    for( var i=0;i< pzh.length; i++)
    {
        var row= dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row,{id: newGUID() , gguid:gguid , inner_xh: i+1 ,  pzh: pzh[i] , code: param.ktbh });
    }                      

    var err= updateAll( dzpz_dy_ds, dzpz_dymx_ds );
    if(err!='')  return{success:false, messager:err};



    var config={ moduleid: moduleid ,//凭证调阅模块代码或ID,
            gguid:gguid,
            flow:'dy', //工作流的代码或ID
            userid: userid, //发起人ID
            subject: `${param.dyr ||''}因 [${param.dyyy ||''}] 调阅凭证`


    };

    var ret= newWork( config ) ;

    if( !ret.success) return ret; 

    //自动递交给初审
     var t = taskInfoForWork('dy', gguid);
        
        //将任务递交下去，如果任务需要签收，则先签收     
        for (var i = 0; i < t.taskList.length; i++) {
            var task = t.taskList[i];

            //可以递交，那么递交下去
            if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
            //需要先签收 ，那么以第一个候选人签收它
            if (task.canClaim) claimWork(moduleid, gguid, task.taskId,  task.candidateUserList[0].userId) ;
            
        }

       ret.id=gguid; 
       return ret; 


}


id: 649ab17599329f5ca7253d3e
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 17:54:10.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDtaStore("", "select 8 from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh || [];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    ret.id = gguid;
    return ret;


}


id: 649ab17599329f5ca7253d55
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 18:05:53.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select 8 from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh || [];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    ret.id = gguid;
    ret.billno= billno;
    return ret;


}


id: 649ab17599329f5ca7253d67
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.27 18:08:03.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select 8 from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    ret.id = gguid;
    ret.billno= billno;
    return ret;


}


id: 649b10f199329f5ca7253d8c
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 09:52:41.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if( ! ds.update(true))
            {
            var errInfo= ds.getError().getMessage(); 
              println( errInfo);
              pushMessage("dr_info", "异常："+errInfo, currentUserId());
              return; 
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649b10f199329f5ca7253d95
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 09:52:46.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if (!ds.update(true)) {
                var errInfo = ds.getError().getMessage();
                println(errInfo);
                pushMessage("dr_info", "异常：" + errInfo, currentUserId());
                return;
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649b93ec9932c5c914b1565d
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 10:13:27.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    runSQL("", " alter table  pzdjex  alter column  bz  varchar(4000) ");

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if (!ds.update(true)) {
                var errInfo = ds.getError().getMessage();
                println(errInfo);
                pushMessage("dr_info", "异常：" + errInfo, currentUserId());
                return;
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649b93ec9932c5c914b15667
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 10:20:37.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    runSQL("", "alter table  pzdjex   modify  bz  varchar(4000) ");

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if (!ds.update(true)) {
                var errInfo = ds.getError().getMessage();
                println(errInfo);
                pushMessage("dr_info", "异常：" + errInfo, currentUserId());
                return;
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649b99e9993276def29fc380
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 10:38:32.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    runSQL("", "alter table  pzdjex   modify  bz  varchar(4000) ");
    runSQL("", "alter table  pzdjex   modify  bz  varchar(1000) ");
    

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if (!ds.update(true)) {
                var errInfo = ds.getError().getMessage();
                println(errInfo);
                pushMessage("dr_info", "异常：" + errInfo, currentUserId());
                return;
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649b99e9993276def29fc389
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 10:39:45.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

    runSQL("", "alter table  pzdjex   modify  bz  varchar(4000) ");
    runSQL("", "alter table  pzdjex   modify  rkdh  varchar(1000) ");
    

    var ds = newDataStore(dsn, "select id,userid,verifiername ,corpid from pzdj where gguid='" + currentGUID() + "'");
    ds.setOnceRetrieveCount(1);
    ds.retrieve('');
    if (ds.getRowCount() == 0) {
        ret.message = '请保存单据后再操作此功能!';
        return ret;
    }

    var corpid = ds.getString(0, "corpid");

    // 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",
        "期间": "m",
        "凭证号": "pzh",
        "调整凭证号": "pzh",
        "会计凭证号": "pzh",
        "凭证日期": "pzrq",
        "会计科目代码": "kmdm",
        "会计科目名称": "kmmc",
        "核算账号编码": "code",
        "借方金额": "jfje",
        "贷方金额": "dfje",
        "财会支出明细编码": "ckzcmxdm",
        "财会支出明细名称": "ckzcmxmc",
        "预会支出明细编码": "ykzcmxdm",
        "预会支出明细名称": "ykzcmxmc",
        "入库单号": "rkdh",
        "是否已过账": "posted",
        "摘要": "bz",
        "制单人": "zdr",
        "经办人": "jbr"
    }

    "年度\t调整期间\t凭证号\t凭证日期\t会计科目代码\t会计科目名称\t财会支出明细编码\t财会支出明细名称\t预会支出明细编码\t预会支出明细名称\t核算账号编码\t入库单号\t是否已过账\t摘要\t制单人";


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

    var excelSheet = excelData;

    //分析字段对应关系
    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));

    pushMessage("dr_info", "开始导入...", currentUserId());

    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(9999999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        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);
        ds.setValue(row, "corpid", corpid);

        if (ds.getRowCount() == 1000) {
            if (!ds.update(true)) {
                var errInfo = ds.getError().getMessage();
                println(errInfo);
                pushMessage("dr_info", "异常：" + errInfo, currentUserId());
                return;
            }
            ds.reset();
        }
    }

    pushMessage("dr_info", "正在写入数据库...", currentUserId());

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

    //更新起始记账期和截止记账期
    var master_ds = newDataStore(dsn, "select * from " + masterTable);
    master_ds.setUpdateProperty(masterTable, "id", "*", "id");
    master_ds.retrieve("gguid='" + currentGUID() + "'");
    master_ds.setValue(0, "jzq_start", getStringFromSQL2(dsn, "select min(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.setValue(0, "jzq_end", getStringFromSQL2(dsn, "select max(y*100+m) as t from pzdjex where gguid='" + currentGUID() + "'"));
    master_ds.update(true)

    pushMessage('dr_info', 'over', currentUserId());

    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: 649bb9cd9932ee4d0f7f5489
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 12:45:17.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    ret.id = gguid;
    ret.billno= billno;
    return ret;


}


id: 649bb9cd9932ee4d0f7f5495
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 12:45:41.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return ret;


}


id: 649bb9cd9932ee4d0f7f54a1
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 12:46:49.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "sa";
    var userid = getUserIdByName(username);
    var leaderid= 1; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 649bbbc19932ee4d0f7f54fa
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 13:00:34.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "api";
    var userid = getUserIdByName(username);
    var leaderid= 21; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select 8 from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    ret.id = gguid;
    ret.billno= billno;
    return ret;


}


id: 649bbbc19932ee4d0f7f5503
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 13:01:25.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "api";
    var userid = getUserIdByName(username);
    var leaderid= 21; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };



    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 649bbbc19932ee4d0f7f5516
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 13:04:31.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = "api";
    var userid = getUserIdByName(username);
    var leaderid= 21; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 649bccb89932ee4d0f7f5569
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:01:49.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg)
{
    println( arg);
    var param= JSON.parse(arg);
    var gguid=  param.id;

    

}


id: 649bd0a39932ee4d0f7f55c6
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:23:11.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);

    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ret= runTask("package", {gguid:gguid}); 
    return  JSON.parse(  ret );
}



function back_urlShare(url , d , t)
{
    var ret= urlShare( url , d, "day", t);
    return ret.url;  
}


id: 649bd0a39932ee4d0f7f55cf
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:24:26.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);

    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ret= runTask("package", {gguid:gguid , userid: currentUserId()}); 
    return  JSON.parse(  ret );
}



function back_urlShare(url , d , t)
{
    var ret= urlShare( url , d, "day", t);
    return ret.url;  
}


id: 649bd0a39932ee4d0f7f55d9
scriptid: 649bccb89932ee4d0f7f5577
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:25:22.000
script:
//后台打包
function main( arg) {
    var param=  JSON.parse(arg);
    var gguid= param.id; 
    

    var ids = [];
    //2022.08.11 优化， 有可能存在重复的，所能加上 distinct 去重
    var $dzpz_dymx_ds = newDataStore("", "select  pz_id ,pzh , max(filenameprefix) as filenameprefix from  dzpz_dymx where gguid='" + gguid + "' group by pz_id, pzh  order by pzh  ");
    $dzpz_dymx_ds.retrieve();
    println($dzpz_dymx_ds.getSelectLastRetrieved());

    for (var i = 0; i < $dzpz_dymx_ds.getRowCount(); i++) {
        var pz_id = '' + $dzpz_dymx_ds.getString(i, "pz_id");
        var filenameprefix = $dzpz_dymx_ds.getString(i, "filenameprefix");
        if (pz_id == '') continue;
        if (ids.contains(pz_id)) continue;
        ids.push({ id:pz_id , filenameprefix: filenameprefix} );
    }

    if (ids.length == 0) {
        println("没有凭证清单");
        return {success:false, message:"没有凭证清单"};
    }

    println(ids.length + "张凭证需要打包");

    var $dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy where gguid='" + gguid + "'");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    $dzpz_dy_ds.retrieve();

    var fileName = $dzpz_dy_ds.getString(0, "reader") + formatDate(newDate(), "yyyy.MM.dd") + "因"+$dzpz_dy_ds.getString(0, "summary") + "调阅凭证.zip";

    var ret = runTask("后台打包", {
        gguid: gguid,
        fileName: fileName,
        ids: ids,
        watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : (formatDate($dzpz_dy_ds.getValue(0, "billdate"), "yyyy.MM.dd HH:mm") + "\n" + $dzpz_dy_ds.getString(0, "watermark")),
        mergePDF: $dzpz_dy_ds.getString(0, "filetype") == 'pdf' //是否合并成一个pdf文件

    });

    println(ret);
    ret = JSON.parse(ret);

    if (ret.success) {
        $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
        $dzpz_dy_ds.update(true);
    }
    return ret;
}


id: 649bd5769932ee4d0f7f5611
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:38:47.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);

    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ret= JSON.parse( runTask("package",{gguid:gguid}));
     
    return ret;
}



function back_urlShare(url , d , t)
{
    var ret= urlShare( url , d, "day", t);
    return ret.url;  
}


id: 649bd5769932ee4d0f7f561a
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 14:39:53.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);

    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ret= JSON.parse( runTask("package",{gguid:gguid}));
    return ret;
}



function back_urlShare(url , d , t)
{
    var ret= urlShare( url , d, "day", t);
    return ret.url;  
}


id: 649be4369932ee4d0f7f57ca
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:43:42.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action= param.action;

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0,"action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret= JSON.parse(  runTask("package", {gguid:gguid , action: action }));
        if( !ret.success) 
        {
            println("打包异常："+ ret.message);
            return ret; 
        }
        return ret ; 

    }

    



}


id: 649be4369932ee4d0f7f57d3
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:44:36.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action= param.action;

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0,"action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret= JSON.parse(  runTask("package", {gguid:gguid , action: action }));
        if( !ret.success) 
        {
            println("打包异常："+ ret.message);
            return ret; 
        }
        return ret ; 

    }

    return {success:false , message:'已打包完成，无需再次打包'};

    



}


id: 649be4369932ee4d0f7f57dc
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:45:36.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
   
    var gguid = p.gguid;
    var topic = "打包下载" + gguid;
     
    var ds=newDataStore("","select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy" , "id","*","id");
    ds.retrieve(" id='"+gguid+"'");
    ds.setValue(0,"ziptaskid","");
    ds.setValue(0,"zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);
      
    pushMessage(topic,  {action:"gameOver",  result:p}, -1);

    //发送消息给申请人
    var html=[];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for( var i=0;i<p.zipFiles.length;i++)
    {
        var url= ''+p.zipFiles[i].url;
        url=url.replace(/&action=view/g , '&action=download');
        html.push('<li><a href="'+url+'" target="_blank">'+p.zipFiles[i].fileName+'</a></li>');
    }
    html.push('</ul>');
    var userid= ds.getInt(0,"userid");
    println( html.join(''));
    chatWith( userid , html.join('')); 

    //
    if( ds.getString(0,"action_after_pack")!='')
    {

        runTask("action_after_pack", {gguid:gguid});
        

}


id: 649be4369932ee4d0f7f57e5
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:45:39.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
   
    var gguid = p.gguid;
    var topic = "打包下载" + gguid;
     
    var ds=newDataStore("","select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy" , "id","*","id");
    ds.retrieve(" id='"+gguid+"'");
    ds.setValue(0,"ziptaskid","");
    ds.setValue(0,"zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);
      
    pushMessage(topic,  {action:"gameOver",  result:p}, -1);

    //发送消息给申请人
    var html=[];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for( var i=0;i<p.zipFiles.length;i++)
    {
        var url= ''+p.zipFiles[i].url;
        url=url.replace(/&action=view/g , '&action=download');
        html.push('<li><a href="'+url+'" target="_blank">'+p.zipFiles[i].fileName+'</a></li>');
    }
    html.push('</ul>');
    var userid= ds.getInt(0,"userid");
    println( html.join(''));
    chatWith( userid , html.join('')); 

    //
    if( ds.getString(0,"action_after_pack")!='')
    {

        runTask("action_after_pack", {gguid:gguid});
    }
    

}


id: 649be4369932ee4d0f7f57ee
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:46:00.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
   
    var gguid = p.gguid;
    var topic = "打包下载" + gguid;
     
    var ds=newDataStore("","select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy" , "id","*","id");
    ds.retrieve(" id='"+gguid+"'");
    ds.setValue(0,"ziptaskid","");
    ds.setValue(0,"zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);
      
    pushMessage(topic,  {action:"gameOver",  result:p}, -1);

    //发送消息给申请人
    var html=[];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for( var i=0;i<p.zipFiles.length;i++)
    {
        var url= ''+p.zipFiles[i].url;
        url=url.replace(/&action=view/g , '&action=download');
        html.push('<li><a href="'+url+'" target="_blank">'+p.zipFiles[i].fileName+'</a></li>');
    }
    html.push('</ul>');
    var userid= ds.getInt(0,"userid");
    println( html.join(''));
    chatWith( userid , html.join('')); 

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if( ds.getString(0,"action_after_pack")!='')
    {

        runTask("action_after_pack", {gguid:gguid});
    }


}


id: 649be56e9932ee4d0f7f5829
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:49:20.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg)
{
    println( arg);
    var param= JSON.parse(arg);
var gguid=param.gguid; 


        var home = getServiceHomeURL( 'app');
 var ds=newDataStore("","select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy" , "id","*","id");
    ds.retrieve(" id='"+gguid+"'");


          var zipResult = ds.getString(0, "zipresult");
        
        zipResult = zipResult.replace(/&action=view/g, '&action=download');
        zipResult = JSON.parse(zipResult);
         let share=[];
        for (var i = 0; i < zipResult.length; i++) {
            var one = zipResult[i];
            var url = one.url;
            url= home +  url;
    let d= 7;
    let t = 3; 
       var  shareRet= urlShare(s, d , t);
       if( ! shareRet.success) 
       {
           println( shareRet.message);
       }else{
           share.push( '<li>'+ shareRet.url +  "  " + one.filename  +"</li>"); 
       }

     

        }
    }


id: 649be56e9932ee4d0f7f5832
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:49:27.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid;


    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    let share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        let d = 7;
        let t = 3;
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }



    }
}


id: 649be56e9932ee4d0f7f583b
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 15:50:39.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid;


    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    let share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        let d = 7;  // 7天有效
        let t = 3;  // 3 次下载 
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action= ds.getString(0,"action_after_pack");

    if( action=='sendMail')
    {



    }
}


id: 649be56e9932ee4d0f7f5844
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:01:41.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid;


    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    let share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        let d = 7;  // 7天有效
        let t = 3;  // 3 次下载 
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be56e9932ee4d0f7f584d
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:01:56.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid;


    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        let d = 7;  // 7天有效
        let t = 3;  // 3 次下载 
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be56e9932ee4d0f7f5856
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:02:35.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid;


    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be56e9932ee4d0f7f585f
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:04:11.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(s, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be9859932ee4d0f7f5879
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:05:03.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(url, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be9859932ee4d0f7f5882
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:11:13.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(url, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");
    println( action);

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getgString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be9859932ee4d0f7f588b
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:11:36.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(url, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");
    println( action);

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getString(0, "flow_instance_subject"),
                body: share.join("<br>"),
                attachments: [{ name: '销售日报.pdf', url: ret.url }]

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be9859932ee4d0f7f5894
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:12:06.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(url, d, t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");
    println( action);

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getString(0, "flow_instance_subject"),
                body: share.join("<br>") 

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 649be9859932ee4d0f7f589d
scriptid: 649bdd0c9932ee4d0f7f571f
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.06.28 16:15:18.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.gguid || '963132457484690360';
    println( " gguid="+ gguid);

    var home = getServiceHomeURL('app');
    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");


    var zipResult = ds.getString(0, "zipresult");

    zipResult = zipResult.replace(/&action=view/g, '&action=download');
    zipResult = JSON.parse(zipResult);
    var  share = [];
    for (var i = 0; i < zipResult.length; i++) {
        var one = zipResult[i];
        var url = one.url;
        url = home + url;
        var d = 7;  // 7天有效
        var t = 3;  // 3 次下载 
        var shareRet = urlShare(url, d,'day', t);
        if (!shareRet.success) {
            println(shareRet.message);
        } else {
            share.push('<li>' + shareRet.url + "  " + one.filename + "</li>");
        }

    }

    var action = ds.getString(0, "action_after_pack");
    println( action);

    if (action == 'sendMail') {

        var config = {
            from: { userid: 1 },
            to: { mailAccount: ds.getString(0, "email") },
            mail: {
                subject: ds.getString(0, "flow_instance_subject"),
                body: share.join("<br>") 

            }
        };

        var ret = sendMail(config);
        return ret;


    }

}


id: 64a3eb0b9932ee4d0f7f630c
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.04 17:53:09.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action= param.action;

    println( gguid);

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0,"action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret= JSON.parse(  runTask("package", {gguid:gguid , action: action }));
        if( !ret.success) 
        {
            println("打包异常："+ ret.message);
            return ret; 
        }
        return ret ; 

    }

    return {success:false , message:'已打包完成，无需再次打包'};

    



}


id: 64a3eb0b9932ee4d0f7f6315
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.04 17:53:16.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action= param.action;

    println( "gguid="+ gguid);

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0,"action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret= JSON.parse(  runTask("package", {gguid:gguid , action: action }));
        if( !ret.success) 
        {
            println("打包异常："+ ret.message);
            return ret; 
        }
        return ret ; 

    }

    return {success:false , message:'已打包完成，无需再次打包'};

    



}


id: 64a3ef6e9932ee4d0f7f636e
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.04 18:09:40.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action= param.action;

    println( "gguid="+ gguid);

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0,"action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret= JSON.parse(  runTask("package", {gguid:gguid , action: action }));
        if( !ret.success) 
        {
            println("打包异常："+ ret.message);
            return ret; 
        }
        return ret ; 

    }


     runTask("action_after_pack", {gguid:gguid});
    return {success:true , message:'已打包完成，无需再次打包,邮件已再次发送'};

    



}


id: 64a53ef18b10ede23ae6083b
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 10:30:03.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg)
{
    println( arg);
    var param= JSON.parse(arg);
   
   var url="https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



	var content = '<?xml version="1.0" encoding="utf-8"?>'+
					'<soap12:Envelope'+
					'    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '+
					'    xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
					'    xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> '+
					'    <soap12:Body>'+
					'        <getMobileCodeInfo'+
					'            xmlns="http://WebXml.com.cn/">'+
					'            <mobileCode>'+tel+'</mobileCode>'+
					'            <userID></userID>'+
					'        </getMobileCodeInfo>'+
					'    </soap12:Body>'+
					'</soap12:Envelope>';



	var ret= httpPost( url , {
		   header:{'Content-Type':'application/soap+xml;charset=utf-8'},
		   body:content
	   });


	println( ret.response);
	var js= xml2json(ret.response);

}


id: 64a778aa8b10ede23ae60846
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 11:08:45.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = '<?xml version="1.0" encoding="utf-8"?>' +
        '<soap12:Envelope' +
        '    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
        '    xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
        '    xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> ' +
        '    <soap12:Body>' +
        '        <ObtainOAinformation' +
        '            xmlns="https://webservices.fzzwsoahd.weaver.com.cn">' +
        '            <in0>146146</in0>' +
        '            <in1>false</in1>' +
        '        </ObtainOAinformation>' +
        '    </soap12:Body>' +
        '</soap12:Envelope>';



    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae6084f
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:33:38.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>

<con:testSuite id="1356a436-7cd8-466d-aa40-b54757bed452" name="FzzwsOAHdServiceHttpBinding TestSuite" xmlns:con="http://eviware.com/soapui/config"><con:settings/><con:runType>SEQUENTIAL</con:runType><con:testCase id="b2eb52bd-64fb-48f2-968f-c2e29ab90455" failOnError="true" failTestCaseOnErrors="true" keepSession="false" maxResults="0" name="ObtainOAinformation TestCase" searchProperties="true"><con:settings/><con:testStep type="request" id="96b0ce85-b4c8-477a-bf8d-ec98a87cae3f" name="ObtainOAinformation"><con:settings/><con:config xsi:type="con:RequestStep" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><con:interface>FzzwsOAHdServiceHttpBinding</con:interface><con:operation>ObtainOAinformation</con:operation><con:request name="ObtainOAinformation" id="8916b91a-b831-4521-bbf7-6d7476b8717d"><con:settings/><con:encoding>UTF-8</con:encoding><con:endpoint>http://oa.cemps.ac.cn/services/FzzwsOAHdService</con:endpoint><con:request><![CDATA[<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="webservices.fzzwsoahd.weaver.com.cn">\r
   <soapenv:Header/>\r
   <soapenv:Body>\r
      <web:ObtainOAinformation>\r
         <web:in0>999999</web:in0>\r
         <web:in1>true</web:in1>\r
      </web:ObtainOAinformation>\r
   </soapenv:Body>\r
</soapenv:Envelope>]]></con:request><con:credentials><con:authType>No Authorization</con:authType></con:credentials><con:wsaConfig action="webservices.fzzwsoahd.weaver.com.cn/FzzwsOAHdServicePortType/ObtainOAinformationRequest"/></con:request></con:config></con:testStep><con:properties/></con:testCase><con:properties/></con:testSuite>
    `



    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae60858
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:34:19.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>

<con:testSuite id="1356a436-7cd8-466d-aa40-b54757bed452" name="FzzwsOAHdServiceHttpBinding TestSuite" 
xmlns:con="http://eviware.com/soapui/config">
<con:settings/>
<con:runType>SEQUENTIAL</con:runType>
<con:testCase id="b2eb52bd-64fb-48f2-968f-c2e29ab90455" failOnError="true" failTestCaseOnErrors="true" 
keepSession="false" maxResults="0" name="ObtainOAinformation TestCase" searchProperties="true">
<con:settings/>
<con:testStep type="request" id="96b0ce85-b4c8-477a-bf8d-ec98a87cae3f" name="ObtainOAinformation"><con:settings/><con:config xsi:type="con:RequestStep" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><con:interface>FzzwsOAHdServiceHttpBinding</con:interface><con:operation>ObtainOAinformation</con:operation><con:request name="ObtainOAinformation" id="8916b91a-b831-4521-bbf7-6d7476b8717d"><con:settings/><con:encoding>UTF-8</con:encoding><con:endpoint>http://oa.cemps.ac.cn/services/FzzwsOAHdService</con:endpoint><con:request><![CDATA[<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="webservices.fzzwsoahd.weaver.com.cn">\r
   <soapenv:Header/>\r
   <soapenv:Body>\r
      <web:ObtainOAinformation>\r
         <web:in0>999999</web:in0>\r
         <web:in1>true</web:in1>\r
      </web:ObtainOAinformation>\r
   </soapenv:Body>\r
</soapenv:Envelope>]]></con:request><con:credentials><con:authType>No Authorization</con:authType></con:credentials><con:wsaConfig action="webservices.fzzwsoahd.weaver.com.cn/FzzwsOAHdServicePortType/ObtainOAinformationRequest"/></con:request></con:config></con:testStep><con:properties/></con:testCase><con:properties/></con:testSuite>
    `



    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae60861
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:55:00.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  
    xmlns:web="webservices.fzzwsoahd.weaver.com.cn">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ObtainOAinformation>
         <web:in0><![CDATA[99999]]></web:in0>
         <web:in1><![CDATA[true]]></web:in1>
      </web:ObtainOAinformation>
   </soapenv:Body>
</soapenv:Envelope>
`


    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae6086a
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:55:46.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  
    xmlns:web="webservices.fzzwsoahd.weaver.com.cn">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ObtainOAinformation>
         <web:in0>99999</web:in0>
         <web:in1>true></web:in1>
      </web:ObtainOAinformation>
   </soapenv:Body>
</soapenv:Envelope>
`


    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae60873
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:57:04.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  
    xmlns:web="webservices.fzzwsoahd.weaver.com.cn">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ObtainOAinformation>
         <web:in0>${requestid}</web:in0>
         <web:in1>true></web:in1>
      </web:ObtainOAinformation>
   </soapenv:Body>
</soapenv:Envelope>
`


    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;
    println(ret.response);
    var js = xml2json(ret.response);
    return js;
}


id: 64a778aa8b10ede23ae6087c
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 12:57:26.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);

    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  
    xmlns:web="webservices.fzzwsoahd.weaver.com.cn">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ObtainOAinformation>
         <web:in0>${requestid}</web:in0>
         <web:in1>true></web:in1>
      </web:ObtainOAinformation>
   </soapenv:Body>
</soapenv:Envelope>
`


    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;

}


id: 64a79cef8b10ede23ae608f4
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 13:32:24.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 21; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64a79cef8b10ede23ae60903
scriptid: 64a53ef18b10ede23ae607f1
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 13:34:42.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var requestid= param.requestid ;
    
    var url = "https://oa.cemps.ac.cn/services/FzzwsOAHdService?wsdl";



    var content = `
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  
    xmlns:web="webservices.fzzwsoahd.weaver.com.cn">
   <soapenv:Header/>
   <soapenv:Body>
      <web:ObtainOAinformation>
         <web:in0>${requestid}</web:in0>
         <web:in1>true></web:in1>
      </web:ObtainOAinformation>
   </soapenv:Body>
</soapenv:Envelope>
`


    var ret = httpPost(url, {
        header: { 'Content-Type': 'application/soap+xml;charset=utf-8' },
        body: content
    });

    return ret.response;

}


id: 64a7aaef8b10ede23ae60cd0
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 14:14:54.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;


    //自动递交给调阅步骤

    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }

    return { success: false, message: '已打包完成，无需再次打包' };





}


id: 64a7aaef8b10ede23ae60cd9
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.07 14:15:40.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;


    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: false, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }

    return { success: false, message: '已打包完成，无需再次打包' };





}


id: 64a7d85e9932ee4d0f7f65dd
scriptid: 60fa600f9932563b7c99baff
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.11 13:35:23.000
script:
/**
 * 单据点击保存，前端所有的操作被转译成3种操作:insert , delete , update ,
 *  并且可以在  beforeBillSaveOnServer 中返回一些SQL语句，可以在afterBillSaveOnServer中返回一些SQL语句
 *
 * 系统分别在需要的数据库连接中执行这些语句 ， 当所有语句执行成功后，事件被提交。一些细节如下 ：
 *
 * 1 如果单据中的表，属于不同的数据库连接，那么所有的SQL语句会以连接为单位，对语句进行批量执行
 * 2 这些语句的执行顺序是：对同一个数据库连接中的语句， 先执行 beforeBillSaveOnServer 中返回的SQL语句，再执行单据操作转译得到的SQL语句，
 *   再执行 afterBillSaveOnServer 中返回的SQL语句， 当多个（或一个）数据库连接执行完这些语句，且没有错误时，所有的数据库连接做提交，否则全部回滚
 * 3 不要在 beforeBillSaveOnServer 或 afterBillSaveOnServer 中直接执行数据库操作，而是返回SQL语句，让系统批量执行它们，并控制好事务
 * 4 当执行成功后，系统再执行事件函数  afterBillSaveSuccessfulOnServer 。 此事件中可以执行任意操作，它与单据保存事件结束后才被触发执行，
 *   与单据保存并不在一个事务中。
 *
 *
 * @param gguid  要删除记录的gguid ，等同于主表的id
 * @param session  一个JSON对象，用于在整个单据保存过程中的各个事件之间传递数据。本事件做为单据保存的最后一个事件，session对象在使用后将被丢弃
 *
 *
 * @return 本函数不需要返回值
 *
 */
function afterBillSaveSuccessfulOnServer(gguid, session) {

    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    //2022.08.11优化，理论上不应该存在重复号码的凭证，但是加上max肯定没错，避免数据异常导致更新失败
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
    "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  "

    ];

    runSQL("", sqls, true);
    println("----检测凭证是否存在完成---------")
}


/**
 * 用户任务提交后
 * @param flow 流程定义
 * @param node 开始节点
 * @param gguid 单据的gguid

 */
//@comment (group=工作流事件,caption=用户任务提交后)
function onUserTaskSubmitted(flow, userTask, gguid) {
    // println( flow.id) ; //流程定义的ID
    // println( userTask.name);
    println(JSON.stringify(userTask));
    println(gguid);


    if (userTask.id == 'id_60b3b08f27644fc18af35ba20ecd2bac') {
        var moreData = getStringFromSQL("select moredata from dzpz_dy where id='" + gguid + "'");
        try {
            moreData = JSON.parse(moreData);
            //起草后，递交后调用OA的接口回写数据
            if (moreData.form_id) {
                runTask('oa_callback', { requestid: moreData.form_id });
            }
        } catch (err) {

        }

    }


    if (userTask.id == 'id_6655df8bedc641aa9bacf1720d13ce2d') //领导审批通过后，就开始打包
    {
        //领导审批通过后，就开始打包
        do_package(gguid);
    }

    println(gguid + " " + userTask.name + " 提交完成")


}

//后台打包
function do_package(gguid) {
    var ret = JSON.parse(runTask("package", { gguid: gguid }));
    return ret;
}



function back_urlShare(url, d, t) {
    var ret = urlShare(url, d, "day", t);
    return ret.url;
}


id: 64a7d85e9932ee4d0f7f65fb
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.11 13:38:03.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 21; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid )
         , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64acc3ca8b10ede23ae60eed
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 10:53:52.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 17; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64acc3ca8b10ede23ae60ef6
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 10:55:54.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: username, billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64acc3ca8b10ede23ae60eff
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 10:56:59.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid  , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64acc3ca8b10ede23ae60f08
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 10:57:10.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid )
         , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: param.ktbh });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64acc8008b10ede23ae60f9f
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 11:21:53.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;


    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }

    return { success: true, message: '已打包完成，无需再次打包' };


true


}


id: 64accb388b10ede23ae60fa8
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.11 11:23:36.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;


    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }

    return { success: true, message: '打包完成' };


 

}


id: 64ad00839932ee4d0f7f66ff
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 39.170.92.207
username: sa
createdate: 2023.07.13 10:53:53.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

    // println(  ds.getJSONRow(0,true));
    var action_after_pack = ds.getString(0, "action_after_pack");
    println("action_after_pack=" + action_after_pack);

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (action_after_pack != '') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    } else {
        println("打包完成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64ad08348b10ede23ae61247
scriptid: 649a906999329f5ca7253b6b
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.12 14:19:14.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);


    var ktbh = param.ktbh || '';
    ktbh= khbh.split(',');
    ktbh="('" + ktbh.join("','")+"')" ;

    if (!param.pzh) return { success: false, message: '没有提供凭证号' };

    var tmpTableName = "t_" + newGUID();
    runSQL("", `drop table  ${tmpTableName}`);
    runSQL("", `create table  ${tmpTableName} ( pzh varchar(40) not null , primary key(pzh)) `);


    for (var i = 0; i < param.pzh.length; i++) {
        var pzh = param.pzh[i];
        runSQL("", `insert into  ${tmpTableName}  ( pzh)  values  ('${pzh}') `);
    }

    try {
        var ds = newDataStore("", `select pzh from ${tmpTableName} a  where not exists ( select b.pzh from pzdjex b  where b.pzh = a.pzh and b.code in  ${ktbh} ) `);
        ds.retrieve();
        if (ds.getRowCount() == 0) {
            ds = newDataStore("", `select pzh from ${tmpTableName} a  where not exists ( select b.pzh from  dzpz_pz b  where b.pzh = a.pzh  ) `);
            ds.retrieve();
            if (ds.getRowCount() == 0) {
                return { success: true, code:'0', messager: `所有凭证号合法，且已影像化` };
            } else {
                var pzhs = [];
                for (var i = 0; i < ds.getRowCount(); i++) {
                    pzhs.push(ds.getString(i, "pzh"));
                }
                runSQL("", `drop table  ${tmpTableName}`);
                return { success: false, code:'1', message: `凭证号合法，但系统中不存在如下凭证的影像资料：${pzhs.join(',')}` };

            }
        }


        var pzhs = [];
        for (var i = 0; i < ds.getRowCount(); i++) {
            pzhs.push(ds.getString(i, "pzh"));
        }
        runSQL("", `drop table  ${tmpTableName}`);
        return { success: false, code:'2'  , message: `系统中不存在课题号为 ${ktbh} 的凭证：${pzhs.join(',')}` };


    }
    catch (err) {

    } finally {
        runSQL("", `drop table  ${tmpTableName}`);
    }


}


id: 64ae47c68b10ede23ae61265
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.12 14:27:19.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid )
         , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param)
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        var code= getStringFromSQL("select code from pzdjex b  where  pzh = '"+pzh[i]+"'");
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: code  });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64ae47c68b10ede23ae61292
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.12 15:05:53.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);


    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (ds.getString(0, "action_after_pack") != '') {

        runTask("action_after_pack", { gguid: gguid });
    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64ae47c68b10ede23ae6129b
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.12 15:06:18.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);


    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (ds.getString(0, "action_after_pack") != '') {
        runTask("action_after_pack", { gguid: gguid });
    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64ae47c68b10ede23ae612a4
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.12 15:06:55.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);


    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (ds.getString(0, "action_after_pack") != '') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af632d8b10ede23ae612ca
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:36:30.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

    println(  ds.getJSONRow(0,true));
    println( "action_after_pack="+ds.getString(0, "action_after_pack"));

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (ds.getString(0, "action_after_pack") != '') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包染成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af632d8b10ede23ae612d3
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:36:45.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

   // println(  ds.getJSONRow(0,true));
    println( "action_after_pack="+ds.getString(0, "action_after_pack"));

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (ds.getString(0, "action_after_pack") != '') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包染成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af632d8b10ede23ae612e2
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:44:33.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

   // println(  ds.getJSONRow(0,true));
   var action_after_pack = ds.getString(0, "action_after_pack");
    println( "action_after_pack="+ action_after_pack);

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (action_after_pack !='') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包染成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af632d8b10ede23ae612eb
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:44:57.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

   // println(  ds.getJSONRow(0,true));
   var action_after_pack = ds.getString(0, "action_after_pack");
    println( "action_after_pack="+ action_after_pack);

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (action_after_pack !='') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包完成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af67ad8b10ede23ae6133a
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:56:49.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    ds.update(true);

    pushMessage(topic, { action: "gameOver", result: p }, -1);

   println(ds.getJSONRow(0, true).replace(/,/g , '<br>'));
   var action_after_pack = ds.getString(0, "action_after_pack");
    println( "action_after_pack="+ action_after_pack);

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (action_after_pack !='') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包完成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af67ad8b10ede23ae61343
scriptid: 6181ea0bc76eefddf45ea1e5
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 10:57:28.000
script:
function main(arg) {

    println(arg);
    var p = JSON.parse(arg);

    var gguid = p.gguid;
    var topic = "打包下载" + gguid;

    var ds = newDataStore("", "select * from dzpz_dy");
    ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    ds.retrieve(" id='" + gguid + "'");
    ds.setValue(0, "ziptaskid", "");
    ds.setValue(0, "zipresult", JSON.stringify(p.zipFiles));
    if(!ds.update(true)) println( ds.getError().getMessage());

    pushMessage(topic, { action: "gameOver", result: p }, -1);

   println(ds.getJSONRow(0, true).replace(/,/g , '<br>'));
   var action_after_pack = ds.getString(0, "action_after_pack");
    println( "action_after_pack="+ action_after_pack);

    // 因为打包是异步的，所以打包后续动作放在这里处理
    if (action_after_pack !='') {
        println('发送邮件');
        runTask("action_after_pack", { gguid: gguid });
    }else{
        println("打包完成，无需后续操作");

    }

    //发送消息给申请人
    var html = [];
    html.push("调阅申请已审批通过，点击链接下载：<br><ul>");
    for (var i = 0; i < p.zipFiles.length; i++) {
        var url = '' + p.zipFiles[i].url;
        url = url.replace(/&action=view/g, '&action=download');
        html.push('<li><a href="' + url + '" target="_blank">' + p.zipFiles[i].fileName + '</a></li>');
    }
    html.push('</ul>');
    var userid = ds.getInt(0, "userid");
    println(html.join(''));
    chatWith(userid, html.join(''));



}


id: 64af67ad8b10ede23ae6135d
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 16:49:51.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid )
         , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param),
        action_after_pack:'sendMail'
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
        var code= getStringFromSQL("select code from pzdjex b  where  pzh = '"+pzh[i]+"'");
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i], code: code  });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


id: 64afbf848b10ede23ae613c0
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.13 17:14:40.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;


    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }
     
    println('发送邮件');
    runTask("action_after_pack", { gguid: gguid });

    return { success: true, message: '打包完成' };


 

}


id: 64b8d76f8b10ede23ae6148b
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.20 17:02:04.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;

    if( id=='') return { success: true, message: 'id不能为空' };

    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }
     
    println('发送邮件');
    runTask("action_after_pack", { gguid: gguid });

    return { success: true, message: '打包完成' };


 

}


id: 64b8d76f8b10ede23ae61494
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.20 17:03:47.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;

    if( id=='') return { success: false, message: 'id不能为空' };

    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    if( t.taskList ==null)  return { success: false, message: 'id 对应的调阅申请不存在' };

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }
     
    println('发送邮件');
    runTask("action_after_pack", { gguid: gguid });

    return { success: true, message: '打包完成' };


 

}


id: 64b8ffe78b10ede23ae61585
scriptid: 649bbbc19932ee4d0f7f5520
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.20 17:35:36.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = param.id;
    var action = param.action;

    if (id == '') return { success: false, message: 'id不能为空' };

    //自动递交给调阅步骤
    var moduleid = 'dy';//模块ID
    var t = taskInfoForWork('dy', gguid);

    if (t.taskList == null) return { success: false, message: 'id 对应的调阅申请不存在' };

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }

    //打包分享

    var $dzpz_dy_ds = newDataStore("", "select * from dzpz_dy");
    $dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");

    $dzpz_dy_ds.retrieve(" id='" + gguid + "'");

    $dzpz_dy_ds.setValue(0, "action_after_pack", action);
    $dzpz_dy_ds.update(true);

    var ziptaskid = $dzpz_dy_ds.getString(0, "ziptaskid");
    if (ziptaskid != '') {
        return { success: true, message: "正在打包压缩中...，请稍候" };
    }

    var zipResult = $dzpz_dy_ds.getString(0, "zipresult");
    if (zipResult == '') {

        println("开始打包");

        var ret = JSON.parse(runTask("package", { gguid: gguid, action: action }));
        if (!ret.success) {
            println("打包异常：" + ret.message);
            return ret;
        }
        return ret;

    }

    println('发送邮件');
    runTask("action_after_pack", { gguid: gguid });

    return { success: true, message: '打包完成' };




}


id: 64b8ffe78b10ede23ae615c2
scriptid: 649aa52d99329f5ca7253c1c
tablename: app_script
clientip: 0:0:0:0:0:0:0:1
username: sa
createdate: 2023.07.20 18:48:07.000
script:
/**
 * 脚本中心的脚本，以 main函数为执行入口，相关的参数放在arg中，它是一个JSON字符串化后的数据
 *
 */
function main(arg) {
    println(arg);
    var param = JSON.parse(arg);
    var gguid = newGUID();
    var moduleid = 'dy';//模块ID
    var username = getProperty( "/API创建调阅流程的起草人",  param.creator || "api");
    var userid = getUserIdByName(username);
    var leaderid= 18; //审核人ID
    var billno = newBillNo('', 'dzpz_dy', 'billno', '{11111111}', 'billdate', newDate(), "");
    var dzpz_dy_ds = newDataStore("", "select * from  dzpz_dy");
    dzpz_dy_ds.setUpdateProperty("dzpz_dy", "id", "*", "id");
    dzpz_dy_ds.insertRow(0);
    dzpz_dy_ds.setValue(0, {
        id: gguid, gguid: gguid, userid: userid, username: getStringFromSQL("select showname from app_user where id="+ userid )
         , billdate: newDate(), billno: billno,
        reader: param.dyr, 
        leaderid: leaderid , 
        summary: param.dyyy, corpid: '00',
        needwatermark: 0,//不打水印 
        filetype: 'zip', // 
        email: param.email,
        moredata: JSON.stringify(param.callback_param),
        action_after_pack:'sendMail'
    });

    var dzpz_dymx_ds = newDataStore("", "select * from dzpz_dymx");
    dzpz_dymx_ds.setUpdateProperty('dzpz_dymx', 'id', '*', "id");
    var pzh = param.pzh  ;
    if( pzh==undefined) pzh =[];
    for (var i = 0; i < pzh.length; i++) {
        var row = dzpz_dymx_ds.insertRow(9999999);
       // var code= getStringFromSQL("select code from pzdjex b  where  pzh = '"+pzh[i]+"'");
        dzpz_dymx_ds.setValue(row, { id: newGUID(), gguid: gguid, inner_xh: i + 1, pzh: pzh[i]    });
    }

    var err = updateAll(dzpz_dy_ds, dzpz_dymx_ds);
    if (err != '') return { success: false, messager: err };


    var corpid = getStringFromSQL("select corpid from dzpz_dy where id='" + gguid + "'");
    
    runSQL(""," update dzpz_dymx  set   code=  ( select min(b.code) as code  from pzdjex b  where  b.pzh =dzpz_dymx.pzh ) where  dzpz_dymx.gguid='" + gguid + "' " );
    var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select max(id) from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh and dzpz_pz.corpid='" + corpid + "' ) where gguid='" + gguid + "' ",
                "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh  and dzpz_pz.corpid='" + corpid + "')  " 
             
    ];
    runSQL("", sqls); 


    var config = {
        moduleid: moduleid,//凭证调阅模块代码或ID,
        gguid: gguid,
        flow: 'dy', //工作流的代码或ID
        userid: userid, //发起人ID
        subject: `${param.dyr || ''}因 [${param.dyyy || ''}] 调阅凭证`


    };

    var ret = newWork(config);

    if (!ret.success) return ret;

    //自动递交给初审
/*
    var t = taskInfoForWork('dy', gguid);

    //将任务递交下去，如果任务需要签收，则先签收     
    for (var i = 0; i < t.taskList.length; i++) {
        var task = t.taskList[i];

        //可以递交，那么递交下去
        if (task.canSubmit) println(submitWork(moduleid, gguid, task.taskId));
        //需要先签收 ，那么以第一个候选人签收它
        if (task.canClaim) claimWork(moduleid, gguid, task.taskId, task.candidateUserList[0].userId);

    }
*/

    ret.id = gguid;
    ret.billno= billno;
    return {success:true , id: gguid , content:{billno:billno}  };


}


