# app_script_history

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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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

}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


id: 60c058be993270982e9c166b
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.09 14:12:19.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;


function formOpen() {
    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

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

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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



    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}


/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = '';

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


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

}

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

}


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


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

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

    return ret;

}


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

}


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


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

}



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


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

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

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


}


id: 60c05c38993270982e9c1699
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.09 14:24:42.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;


function formOpen() {
    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

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

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}


/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = '';

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}


id: 60c17a7d9932e1a17db2e148
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 10:35:41.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}


id: 60c17a7d9932e1a17db2e15c
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 10:48:44.000
script:
function formOpen()
{
    book.showTabOnWhere="top";
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if ( name=='upload1')
    {
          return { success: true }; //  
    }

    if ( name=='upload2')
    {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}


id: 60c17a7d9932e1a17db2e162
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 10:53:09.000
script:
function formOpen()
{
    book.showTabOnWhere="top";
     book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if ( name=='upload1')
    {
          return { success: true }; //  
    }

    if ( name=='upload2')
    {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
            moveImageToRecycle(data.id);
            var imgPool = book.sheet1.getBrick('upload2');
            imgPool.reInit();
             
    }
    if (name == 'upload2') {
            realDeleteImage(data.id);
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
             
    }

     
    return { success: true };
}


id: 60c17a7d9932e1a17db2e16a
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 10:54:27.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

function  moveImageToRecycle(id)
{
    
    runSQL("pz",  " update dzpz_imgpool_fileupload set info2='回收站' where id='"+id+"'  ",true);

}

function  realDeleteImage(id)
{
    
    runSQL("pz",  " delete from dzpz_imgpool_fileupload  where id='"+id+"'  ",true);

}


id: 60c17a7d9932e1a17db2e172
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 10:55:59.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

function  moveImageToRecycle(id)
{
    
    runSQL("pz",  "update dzpz_imgpool_fileupload set info2='回收站' where id='"+id+"'  ",true);

}

function  realDeleteImage(id)
{
    
    runSQL("pz",  "delete from dzpz_imgpool_fileupload  where id='"+id+"'  ",true);

}


id: 60c182039932e1a17db2e1c0
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 11:08:58.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

function  moveImageToRecycle(id)
{
    
    runSQL("",  "update dzpz_imgpool_fileupload set info2='回收站' where id='"+id+"'  ",true);

}

function  realDeleteImage(id)
{
    
    runSQL("",  "delete from dzpz_imgpool_fileupload  where id='"+id+"'  ",true);

}


id: 60c182039932e1a17db2e1d4
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 11:31:20.000
script:
function formOpen()
{
    book.showTabOnWhere="top";
     book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if ( name=='upload1')
    {
          return { success: true }; //  
    }

    if ( name=='upload2')
    {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
            moveImageToRecycle(data.id);
            var imgPool = book.sheet1.getBrick('upload2');
            imgPool.reInit();
             
    }
    if (name == 'upload2') {
            realDeleteImage(data.id);
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
             
    }

     
    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c182039932e1a17db2e1da
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 11:33:38.000
script:
function formOpen() {
    book.showTabOnWhere = "top";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        var imgPool = book.sheet1.getBrick('upload2');
        imgPool.reInit();
        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c182039932e1a17db2e1e0
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 11:36:36.000
script:
function formOpen() {
    book.showTabOnWhere = "top";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();
        
        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c1b7889932e1a17db2e2b2
scriptid: 60ab09f85db2f37491f99447
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:05:32.000
script:
/*
得到指定帐套的当前帐期
原理：  获取上一个关帐的年月，如果不存在，那么直接返回本月
        关帐年月的下一个月就是当前活动年月
 */

function main(arg)
{
    var p= JSON.parse( arg);
    var corporationid= p.corporationid ||'';
    println( corporationid);

    var sql= " select  max(ym) from dzpz_gz where   state = 1 and corporationid='"+ corporationid+"' ";
    println( sql);
    var ym= ''+getStringFromSQL2( "pz", sql);
    println(" ym= "+ ym);
   
    if( ym=='') 
    {
        ym =  getIntFromSQL("pz", " select  min(ym) from dzpz_gz where  ifnull(  state,0) = 0 and corporationid='"+ corporationid+"' ");
        if( ym ==0)         ym =  getYear(newDate())*100+ getMonth(newDate());
     //   println( ym);
    }else{
        ym= parseInt(ym);
        var  y = round( ym /100 ,0);
        var m= ym -  y *100;
        m=m+1;
        if( m==13)
        {
            y++;
            m=1;
        }
        ym=  y*100 + m ;
    }

    return ''+ round(ym,0); 


	

}


id: 60c1b7889932e1a17db2e2ba
scriptid: 60ab09f85db2f37491f99447
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:06:34.000
script:
/*
得到指定帐套的当前帐期
原理：  获取上一个关帐的年月，如果不存在，那么直接返回本月
        关帐年月的下一个月就是当前活动年月
 */

function main(arg)
{
    var p= JSON.parse( arg);
    var corporationid= p.corporationid ||'';
    println( corporationid);

    var sql= " select  max(ym) from dzpz_gz where   state = 1 and corporationid='"+ corporationid+"' ";
    println( sql);
    var ym= ''+getStringFromSQL2( "pz", sql);
    println(" ym= "+ ym);
   
    if( ym=='') 
    {
        sql="select  min(ym) from dzpz_gz where  ifnull(  state,0) = 0 and corporationid='"+ corporationid+"' ";
        println(sql);
        ym =  getIntFromSQL("pz", sql);
        if( ym ==0)         ym =  getYear(newDate())*100+ getMonth(newDate());
     //   println( ym);
    }else{
        ym= parseInt(ym);
        var  y = round( ym /100 ,0);
        var m= ym -  y *100;
        m=m+1;
        if( m==13)
        {
            y++;
            m=1;
        }
        ym=  y*100 + m ;
    }

    return ''+ round(ym,0); 


	

}


id: 60c1b7889932e1a17db2e2d0
scriptid: 60ab09f85db2f37491f99447
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:09:46.000
script:
/*
得到指定帐套的当前帐期
原理：  获取上一个关帐的年月，如果不存在，那么直接返回本月
        关帐年月的下一个月就是当前活动年月
 */

function main(arg)
{
    var p= JSON.parse( arg);
    var corporationid= p.corporationid ||'';
    println( corporationid);

    var sql= " select  max(ym) from dzpz_gz where   state = 1 and corporationid='"+ corporationid+"' ";
    println( sql);
    var ym= ''+getStringFromSQL2( "pz", sql);
    println(" ym= "+ ym);
   
    if( ym=='') 
    {
        sql="select  min(ym) from dzpz_gz where  ifnull(  state,0) = 0 and corporationid='"+ corporationid+"' ";
        println(sql);
        ym =  getIntFromSQL2("pz", sql);
        if( ym ==0)         ym =  getYear(newDate())*100+ getMonth(newDate());
     //   println( ym);
    }else{
        ym= parseInt(ym);
        var  y = round( ym /100 ,0);
        var m= ym -  y *100;
        m=m+1;
        if( m==13)
        {
            y++;
            m=1;
        }
        ym=  y*100 + m ;
    }

    return ''+ round(ym,0); 


	

}


id: 60c1bf8e9932e1a17db2e436
scriptid: 60c1bec59932e1a17db2e3da
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:33:50.000
script:
function main(arg)
{
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid= JSON.parse(ret).gguid;
    var url= "billedit?id=toConfirm&limit=trash&gguid="+gguid+"&action=edit";
    return "<script>window.location.href='"+url+"';</script>";
}


id: 60c1bf8e9932e1a17db2e440
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:35:00.000
script:
/**
 * 模板打开时先初始化界面及字段绑定操作，然后再检索数据， 本事件在界面初始化完成，但尚未开始检索数据前执行
 * 此时，模板内容处于不可见状态
 */
function uiInited()
{
    if( urlArgs.limit=='normal')
    {
        book.sheet1.visible=false;
    }

    if( urlArgs.limit=='trash')
    {
        book.setActiveSheet(1);
        book.sheet0.visible=false;
    }

}


function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();
        
        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c1bf8e9932e1a17db2e446
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:36:31.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

    if( urlArgs.limit=='normal')
    {
        book.sheet1.visible=false;
    }

    if( urlArgs.limit=='trash')
    {
        book.setActiveSheet(1);
        book.sheet0.visible=false;
    }

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();
        
        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c1c2469932e1a17db2e47f
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:43:50.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";

    

    if( urlArgs.limit=='trash')
    {
        book.setActiveSheet(1);
        book.sheet0.visible=false;
    }else
    {
book.sheet1.visible=false;
    }

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();
        
        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c1c2469932e1a17db2e485
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 15:43:53.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


id: 60c1c2469932e1a17db2e4a3
scriptid: 60a31c3c5db27838e0c0129e
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:03:01.000
script:
function getImageList1()
{
    return getImageList("凭证");
}
function getImageList2()
{
    return getImageList("附件");
}


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

    return  { success:true,  data:ret};

}


id: 60c1c2469932e1a17db2e4ad
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:04:29.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
book.showTabOnWhere="top";



}

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


id: 60c1c2469932e1a17db2e4b3
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:04:37.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen()
{
book.showTabOnWhere="top";



}

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


id: 60c1c2469932e1a17db2e4c6
scriptid: 60a31c3c5db27838e0c0129e
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:05:49.000
script:
function getImageList1()
{
    return getImageList("凭证");
}
function getImageList2()
{
    return getImageList("附件");
}


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

    return  { success:true,  data:ret};

}


id: 60c1cbaf9932e1a17db2e5c5
scriptid: 60c1cb909932e1a17db2e4cd
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:22:54.000
script:
function main(arg)
{
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid= JSON.parse(ret).gguid;
    var url= "billedit?id=toConfirm&limit=trash&gguid="+gguid+"&action=edit&editToolbarVisible=false";
    return getServiceHomeURL("app") +url ); 
}


id: 60c1cbaf9932e1a17db2e5cd
scriptid: 60c1cb909932e1a17db2e4cd
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:23:00.000
script:
function main(arg)
{
    var ret = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid= JSON.parse(ret).gguid;
    var url= "billedit?id=toConfirm&limit=trash&gguid="+gguid+"&action=edit&editToolbarVisible=false";
    return getServiceHomeURL("app") +url  ; 
}


id: 60c1cbaf9932e1a17db2e5d3
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:23:50.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;


function formOpen() {
    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

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

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}


/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = '';

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c1cbaf9932e1a17db2e5e9
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:27:18.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c1cbaf9932e1a17db2e5f7
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.06.10 16:32:13.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

function  moveImageToRecycle(id)
{
    
    runSQL("",  "update dzpz_imgpool_fileupload set info2='回收站' where id='"+id+"'  ",true);

}

function  realDeleteImage(id)
{
    
    runSQL("",  "delete from dzpz_imgpool_fileupload  where id='"+id+"'  ",true);

}


id: 60c1f9e05db28a5bd97f335f
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:03:23.000
script:
/**
 * 模板打开时先初始化界面及字段绑定操作，然后再检索数据， 本事件在界面初始化完成，但尚未开始检索数据前执行
 * 此时，模板内容处于不可见状态
 */
function uiInited()
{


 

 if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }
}



function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



   

}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c1f9e05db28a5bd97f336b
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:26:38.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                alert(id);
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c1f9e05db28a5bd97f3371
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:36:04.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-pen", "恢复图片", "green", function(id){
                alert(id);
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c1f9e05db28a5bd97f3377
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:36:18.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-edit", "恢复图片", "green", function(id){
                alert(id);
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c216bb5db28a5bd97f34ab
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:44:56.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

function  moveImageToRecycle(id)
{
    
    runSQL("",  "update dzpz_imgpool_fileupload set info2='回收站' where id='"+id+"'  ",true);

}

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


}

function  realDeleteImage(id)
{
    
    runSQL("",  "delete from dzpz_imgpool_fileupload  where id='"+id+"'  ",true);

}


id: 60c216bb5db28a5bd97f34b1
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:45:05.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c216bb5db28a5bd97f34b7
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 21:45:45.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
                upload2.removeItem(id); //仅仅是从界面上移除
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c21b2a5db28a5bd97f34bd
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.3.2
username: sa
createdate: 2021.06.10 22:01:15.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
                toastr.info("图片已还原");
                upload2.removeItem(id); //仅仅是从界面上移除
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要个传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}

function  getPZHPrefix()
{
    return  getProperty("/凭证号/前缀","");
}

function getPZHLen()
{
    return  parseInt(  getProperty("/凭证号/长度","5"));
}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}

//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix()
{
    return  getProperty("/凭证号/前缀","");
}

//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt(  getProperty("/凭证号/长度","5"));
}


id: 60c2ba745db267c2687246ae
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 09:50:37.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

    pzh_len= getPZHLen();
    pzh_prefix=getPZHPrefix();

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

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

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}


/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = '';

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ba745db267c2687246b4
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 09:58:41.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) 
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{

        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}

//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    ym=''+ym; 
    var y= ym.substring(0,4);
    var m= ym.substring(4,6);

    var t = ''+getProperty("/凭证号/前缀","");
    if( t=='') return t; 
    if( t.indexOf("${yy}")>=0)  t=t.replace(/[{]yy[}]/g , y.substring(2,4) );
    if( t.indexOf("${yyyy}")>=0)  t=t.replace(/[{]yyyy[}]/g , y  );
    if( t.indexOf("${mm}")>=0)  t=t.replace(/[{]mm[}]/g , m  );
    return t; 
    
}

//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt(  getProperty("/凭证号/长度","5"));
}


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

}

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

}


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


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

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

    return  { success:true,  data:ret};

}


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

}


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


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

}



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


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

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

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


}

//@comment (group=,caption=凭证号前缀,needRightControl=false)
function  getPZHPrefix(ym)
{
    ym=''+ym; 
    var y= ym.substring(0,4);
    var m= ym.substring(4,6);

    var t = ''+getProperty("/凭证号/前缀","");
    if( t=='') return t; 
    if( t.indexOf("{yy}")>=0)  t=t.replace(/[{]yy[}]/g , y.substring(2,4) );
    if( t.indexOf("{yyyy}")>=0)  t=t.replace(/[{]yyyy[}]/g , y  );
    if( t.indexOf("{mm}")>=0)  t=t.replace(/[{]mm[}]/g , m  );
    return t; 
    
}

//@comment (group=,caption=凭证号长度,needRightControl=false)
function getPZHLen()
{
    return  parseInt(  getProperty("/凭证号/长度","5"));
}


id: 60c2c43f5db267c2687246db
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:05:44.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) 
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            pzh=  stringInc(pzh);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2c43f5db267c2687246e1
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:07:00.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) 
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            pzh=  stringInc(pzh);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2c43f5db267c2687246e7
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:10:04.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}


/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) 
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  findLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2c43f5db267c2687246ed
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:19:37.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) 
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


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

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

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

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

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

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


}


id: 60c2ca365db267c26872472b
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:45:24.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c268724731
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:46:47.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
                
                return null;
            }
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c268724737
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:48:35.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
                
                return null;
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c26872473f
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:49:10.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
                
                return false;
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c268724749
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:49:22.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
                
                return false;
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c26872474f
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:51:08.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
                
                return false;
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2ca365db267c268724780
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 10:59:12.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
        pzh = g_lastPZH;

        if( pzh=='') //说明还没有输入过一次凭证号
        {
            pzh= pzh_prefix; 
        }else{
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        }

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
           
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
         
              
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
          
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2d2145db267c268724786
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 11:01:40.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix=""; // 凭证号前缀
var pzh_len =0; //凭证号长度

function formOpen() {

   

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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if ( name=='imgPool')
    {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id)
{
    let imgPool=book.sheet1.getBrick("imgPool");
    let imgs= imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index=0;
    for( let i=0;i<imgs.length;i++)
    {
        if( imgs[i].id==id)
        {
            index=i;
            break; 
        }
    }
    
    //再从index往左边查到第一张凭证
    for(let i= index-1;i>=0;i--)
    {
        let tid= imgs[i].id;
        let pzh= getPZH(tid);
        if( pzh=='') continue;
        if( i == index -1) 
        {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        }else{
            return stringInc( pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

   // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH="";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh="";
    if( pzh=='')
    {
         
            //找到左边最近的一张凭证号
            //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
            //否则在那个号上加1做为自已的凭证号
            pzh=  incLeftNearestPZH(id);
        

    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {
            
            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
           
        } else {
            if( val.length!= pzh_len)
            {
                toastr.error("凭证号长度必须是"+pzh_len+"位");
         
              
            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
          
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true);}
function cb_selectnull_onClick() { doSelect(false);}

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {
   
    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset=0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示","确信删除本凭证，并将图片全部回归到待归档状态吗?", function(){
    book.sheet3.getBrick('cb_delete_pz').visible = false;
    var id = $one_ds.getString(0, "id");
    var ret = deletePZAndPutBackToPool(id);
    if (ret.success) {
        $one_ds.reset();
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
        var FJ = book.sheet3.getBrick('FJ');
        FJ.config.action = 'view';
        FJ.buildGridly([]);
        cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' ||  cell.alias == "rq" ) {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function  cb_trash_onClick()
{
    var url=  runTask("urlForTrash", {});
    openInMainFrame(url , false, 'fa-trash', '图片回收站' );

}


id: 60c2d2145db267c26872478c
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 11:01:43.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度

function formOpen() {



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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

    // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(id);


    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);

        } else {
            if (val.length != pzh_len) {
                toastr.error("凭证号长度必须是" + pzh_len + "位");


            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);

        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}


id: 60c2d2145db267c268724792
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 11:02:33.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度

function formOpen() {



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

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

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

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

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

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

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

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

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


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

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

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

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

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

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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}


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

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

        }
    }

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


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

    // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);


    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);

        } else {
            if (val.length != pzh_len) {
                toastr.error("凭证号长度必须是" + pzh_len + "位");


            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);

        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

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


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}


id: 60c2d2145db267c26872479a
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 11:13:33.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度

function formOpen() {



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

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

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

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

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

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

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

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);
}

// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片控件,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

    // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);


    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length != pzh_len) {
                toastr.error("凭证号长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            lastPZ = {};
            lastPZ.pzh = pzh;
            lastPZ.imgID = one.id;
            lastPZ.fj = [];
            lastPZ.fj.push(one.id); //凭证图片，也加到附件列表中，便于撤销归档
            pzGroup.push(lastPZ);
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}


id: 60c2d2145db267c2687247ad
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 13:49:26.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
                toastr.info("图片已还原");
                upload2.removeItem(id); //仅仅是从界面上移除
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要上传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c2d2145db267c2687247b3
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 13:50:45.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

function imageGridlyBeforeInit(sheet , name, data ) {
    if( name=='upload2')  sheet.getBrick(name).config.uploadButtonDisabled=true; //禁止上传
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
                toastr.info("图片已还原");
                upload2.removeItem(id); //仅仅是从界面上移除
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要上传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c2d2145db267c2687247bc
scriptid: 609d3cfc5db2b0a331d6bb4f
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 14:05:29.000
script:
function formOpen() {
    book.showTabOnWhere = "none";
    book.sheet0.getBrick('upload1').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";
    book.sheet1.getBrick('upload2').config.promptInfoOnDelete = "确信要将图片彻底删除吗?";



    if (urlArgs.limit == 'trash') {
        book.setActiveSheet(1);
        book.sheet0.visible = false;
    } else {
        book.sheet1.visible = false;
    }

    //
    
}

 function imageGridlyBeforeInit(sheet , name, data ) {
    if( name=='upload2')  sheet.getBrick(name).config.uploadButtonDisabled=true; //禁止上传
}


/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet , name, data ) {
    if( name=='upload2')
    {
            let upload2=sheet.getBrick(name);
            upload2.addToolButton( 2,"fa-mail-reply", "恢复图片", "green", function(id){
                moveImageToNormal(id);
                toastr.info("图片已还原");
                upload2.removeItem(id); //仅仅是从界面上移除
            });
    }
}


//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {

    if (name == 'upload1') {
        return { success: true }; //  
    }

    if (name == 'upload2') {
        toastr.info("回收站不需要上传图片");
        return { success: false }; // 此返回，阻止了默认的上传操作
    }

}
//@comment (group=图片控件,caption=图片被删除)
function imageOnDelete(sheet, name, data) {

    if (name == 'upload1') {
        moveImageToRecycle(data.id);
        book.sheet0.getBrick('upload1').reInit();
        book.sheet1.getBrick('upload2').reInit();

        return { success: false };  // 注意 一定要return false   表示不执行默认的操作，

    }
    if (name == 'upload2') {  // 本来 return true  用默认的删除也可以，但是刷新的

        setTimeout(function () {
            var imgPool = book.sheet0.getBrick('upload1');
            imgPool.reInit();
        }, 1000);

        return { success: true };  //    表示执行默认的删除操作，会在数据库中也删除记录，上面延迟刷新
    }


    return { success: false };  // 注意 一定要return false   表示不执行默认的操作，
}


function cb_refresh_onClick()
{
    book.sheet1.getBrick('upload2').reInit();
}


id: 60c2d2145db267c2687247ce
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 192.168.1.140
username: sa
createdate: 2021.06.11 14:26:20.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度

function formOpen() {



    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corporationid = book.sheet2.cells("corporationid").getValueString();
    runTask("当前记帐期", { corporationid: corporationid }, function (ym) {
        book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen();
        pzh_prefix = getPZHPrefix(ym);

        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    });

    book.sheet3.getBrick('FJ').config.promptInfoOnDelete = "确信要将图片从当前凭证中移除，并放回到图片池中吗?";
    book.sheet1.getBrick('imgPool').config.promptInfoOnDelete = "确信要将图片放入回收站吗?";

    //收到来自服务器推送的消息
    onPushMessage("electronPushMessage", function (msg) {
        msg = JSON.parse(msg);
        if (msg.cmd == "newFileUploaded") newImgCommingTipVisible(true); //通知有新文件上传了
        if (msg.cmd == "notifyNeedUploadFileCount") notifyNeedUploadFileCount(msg.fileCount); //通知还有多少个文件等待上传
    });

    //获取当前的electron接口对象
    electron = getElectron(); //getElectron是系统全局功能函数

    book.sheet1.getBrick('imgPool').selectionMode = 'multi'; //图片设置成多选模式

    // 追加一些CSS类 ，用于凭证号标记
    $(document.body).append(`<style>
                        .pzh {position:absolute;left:0;bottom:0px; 
                                height:24px; line-height:24px;width:100%; 
                                background-color:#40af40a0; 
                                color:white;font-weight:bold;font-size:12px;text-align:center;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:14px; top:0; text-align:right; 
                                    vertical-align:top; font-size:12px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);

    setTimeout(function () {
        //调取缩略图大小
        var imgPool = book.sheet1.getBrick('imgPool');

        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit != '') moniteStart(pathToMonit);
        }
    }, 500);
}

// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片控件,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return pzh_prefix;
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data) {

    // book.sheet0.cells("imgPreview").setValue("");
}

var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data) {

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);


    }

    inputBox("标记为凭证", "", pzh, "输入凭证号码", function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length != pzh_len) {
                toastr.error("凭证号长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }

    }, true /*允许为空*/);
}


//@comment (group=,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}


//@comment (group=图片清单刷新,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists) {
    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"><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    var pzGroup = [];
    var pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    var lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        var one = selection[i];
        var pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                lastPZ = pzh2Config[pzh];
            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir(pzGroup);

    $confirm("提示", "确信要归档" + pzGroup.length + "张凭证吗?", function () {
        do_pzgd(pzGroup);
    });


}

//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd(pzGroup) {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    runTask("归档",
        {
            corporationid: book.sheet2.cells("corporationid").getValueString(),
            ym: book.sheet2.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function () {

            hideInfoPane();
            setButtonsStatus(true); //启用一些按钮点击
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            //重新检索图片区
            cb_refresh_onClick();

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

function loadPZ(id, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    FJ.buildGridly(getPZFJ(id));
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}

/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //如果是绑定了数据库的，强烈不建议使用本事件，换用结果集变化事件 itemChanged

    //通过别名来判断
    if (cell.alias == 'pzh' || cell.alias == "rq") {
        smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    }



}


function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}


