# app_script_history

id: 6132e88199321e8a849017ee
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.08 16:48:32.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}


function downloadTemplateFile() {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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



function importFromExcelFile() {
    showInfoPane("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });
}


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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {
        
         
            book.sheet0.paintPermit = false;
            toastr.info("导入完成");
       
    });
}
        
 


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

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




function cb_package_onClick() {

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

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

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

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

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.sheet1.float('fa fa-cog', "凭证检索",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '65%', height: '90%' });

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613878f499321e8a849017f4
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.08 16:48:52.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}


function downloadTemplateFile() {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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



function importFromExcelFile() {
    showInfoPane("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });
}


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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {
        
         
            book.sheet0.paintPermit = false;
            toastr.info("导入完成");
       
    });
}
        
 


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

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




function cb_package_onClick() {

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

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

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

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

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.sheet1.float('fa fa-cog', "凭证检索",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '55%', height: '90%' });

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613878f499321e8a849017fa
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.08 16:49:08.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}


function downloadTemplateFile() {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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



function importFromExcelFile() {
    showInfoPane("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });
}


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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {
        
         
            book.sheet0.paintPermit = false;
            toastr.info("导入完成");
       
    });
}
        
 


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

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




function cb_package_onClick() {

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

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

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

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

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_pzlist_onClick(sheet, cell, button) {
    // if (form.isSaveNeeded()) {
    //     toastr.info("请先保存");
    //     return;
    // }
    book.sheet1.float('fa fa-cog', "凭证检索",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '60%', height: '90%' });

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


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

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}


function downloadTemplateFile() {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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



function importFromExcelFile() {
    showInfoPane("*自动保存，准备导入");
    form.save(false, function () {
        book.readXLS(function (data) {
            showInfoPane("*正在导入");
            setTimeout(function () {
                importData(data);
            }, 10);
        });
    });
}


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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


    showInfoPane("*正在保存并检测凭证号");
    form.save(false, function () {
        
         
            book.sheet0.paintPermit = false;
            toastr.info("导入完成");
       
    });
}
        
 


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

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




function cb_package_onClick() {

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

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

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

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

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_pzlist_onClick(sheet, cell, button) {
    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }
    book.sheet1.float('fa fa-cog', "凭证检索",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '60%', height: '90%' });

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613878f499321e8a84901818
scriptid: 60a321f05db27838e0c014bf
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.10 10:11: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 asc, filename asc ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。
    ds.setOnceRetrieveCount(40);

    var n = ds.retrieve();

    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return { success: true, totalCount: ds.getDBRowCount(), data: ret };

}

function getTotalImageCount() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

    //排除掉回收站的图片
    var sql = "select count(*) as c from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''    ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。


    ds.retrieve();
    println(ds.getSelectLastRetrieved());

    return ds.getInt(0, "c");

}

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

}


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


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

}



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


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

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

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


}

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

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

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


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


function reorderImageFileIndex(imgs) {

}


id: 613dd07799321e8a84901ad8
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.12 18:26:06.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_pzlist_onClick(sheet, cell, button) {
    if (form.isSaveNeeded()) {
        toastr.info("请先保存");
        return;
    }
    book.sheet1.float('fa fa-cog', "凭证检索",
        {
            my: 'right-center',
            at: 'right-center',
            autoposition: 'down',
            offsetX: -5,
            offsetY: 5
        }, { width: '60%', height: '90%' });

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613dd07799321e8a84901ae2
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.12 18:33:57.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613e904199321e8a84902975
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 09:48:02.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613e904199321e8a8490297b
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 09:48:23.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

}

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


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

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613eb57699321e8a849029a5
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 10:27:04.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613ebc6499321e8a84902cbc
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 11:20:46.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';

    onPushMessage("打包下载", function (info) {
        showInfoPane(info);
    })

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

}
/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_downloadTemplateFile_onClick(sheet, cell, button) {
    var title = "序号\t凭证号";
    var data = [];
    data.push(title);
    data.push("1\t0001");
    data.push("2\t0002");

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

    for (let row = dataStartRow; row < RC; row++) {
        let pzh = safeValue(excelSheet, row, 1) || '';
        if (pzh == '') continue;

        let r = $dzpz_dymx_ds.insertRow(99999);
        $dzpz_dymx_ds.setValue(r, "pzh", pzh);
    }


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


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

    });
}




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

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




function cb_package_onClick() {

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

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

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

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

    });

}

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

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

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

    //通过别名来判断
    if (cell.alias == 'st_seletedall') {
        for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
            $q_pzdjex_ds.setValue(i, "selected", newValue);
        }
    }
}

/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
function cb_import_onClick(sheet, cell, button) {
    var row = 0;
    for (var i = 0; i < $q_pzdjex_ds.getRowCount(); i++) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') {
            row = $dzpz_dymx_ds.insertRow(999999);
            $dzpz_dymx_ds.setValue(row, "pzh", $q_pzdjex_ds.getValue(i, "pzh"));
            $dzpz_dymx_ds.setValue(row, "memo", iif($q_pzdjex_ds.getString(i, "code") != "", "核算账号编号：" + $q_pzdjex_ds.getString(i, "code"), null));
        }
    }

    for (var i = $q_pzdjex_ds.getRowCount() - 1; i >= 0; i--) {
        if ($q_pzdjex_ds.getString(i, "selected") == '1') $q_pzdjex_ds.deleteRow(i);
    }
}


id: 613ebc6499321e8a84902cdf
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 11:23:00.000
script:
function main(arg) {

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

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t="*完成" + ((i+1)*100.0/ids.length )+"%";
        println(t);
         pushMessage( "打包下载" , t , currentUserId()); 
         delay(10);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        source.push(t.data);
    }



    println(JSON.stringify(source));
    pushMessage( "打包下载" , "*正在压缩" , currentUserId()); 
    var ret= createZipFileWith(p.fileName, source ,watermark);
    println( JSON.stringify( ret));
    return ret; 

}


id: 613ede889932fcd74154e5e2
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 13:41:50.000
script:
function main(arg) {

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

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t="*完成" + ((i+1)*100.0/ids.length )+"%";
        println(t);
         pushMessage( "打包下载" , t , currentUserId()); 
         delay(10);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        println( JSON.stringify(t));
        source.push(t.data);
    }



    println(JSON.stringify(source));
    pushMessage( "打包下载" , "*正在压缩" , currentUserId()); 
    var ret= createZipFileWith(p.fileName, source ,watermark);
    println( JSON.stringify( ret));
    return ret; 

}


id: 613ede889932fcd74154e5ea
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 13:41:58.000
script:
function main(arg) {

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

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println( (i+1)+"  "+ ids[i]);
        var t="*完成" + ((i+1)*100.0/ids.length )+"%";
        println(t);
         pushMessage( "打包下载" , t , currentUserId()); 
         delay(10);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        println( JSON.stringify(t));
        source.push(t.data);
    }



    println(JSON.stringify(source));
    pushMessage( "打包下载" , "*正在压缩" , currentUserId()); 
    var ret= createZipFileWith(p.fileName, source ,watermark);
    println( JSON.stringify( ret));
    return ret; 

}


id: 613ee4a89932fcd74154e5f2
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 13:42:00.000
script:
function main(arg) {

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

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println((i + 1) + "  " + ids[i]);
        var t = "*完成" + ((i + 1) * 100.0 / ids.length) + "%";
        println(t);
        pushMessage("打包下载", t, currentUserId());
        delay(10);
        var t = createArchive("dzpz", ids[i], false);//把没有归档的归档一下，已经归档的不要重复归档
        println(JSON.stringify(t));
        source.push(t.data);
    }



    println(JSON.stringify(source));
    pushMessage("打包下载", "*正在压缩", currentUserId());
    var ret = createZipFileWith(p.fileName, source, watermark);
    println(JSON.stringify(ret));
    return ret;

}


id: 613ef3801410828210de885b
scriptid: 60d0840b0c749ebb22855746
tablename: app_script
clientip: 192.168.1.93
username: sa
createdate: 2021.09.13 14:48:36.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    var id= p.id;
    var overwrite= p.overwrite; 

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


}


id: 613ef5221410828210de8888
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 192.168.1.93
username: sa
createdate: 2021.09.13 14:54:37.000
script:
var labelDataInited=false;

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


}

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

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


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

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


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


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

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


id: 613f05f2993278d88965739f
scriptid: 60d1732d99326f9120345714
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.13 16:04:03.000
script:
function main(arg) {

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

    var source = [];
    for (var i = 0; i < ids.length; i++) {
        println((i + 1) + "  " + ids[i]);
        var t = "*完成" + ((i + 1) * 100.0 / ids.length) + "%";
        println(t);
        pushMessage("打包下载", t, currentUserId());
        delay(10);
        var t = createArchive("dzpz", ids[i], "",false);//把没有归档的归档一下，已经归档的不要重复归档
        println(JSON.stringify(t));
        source.push(t.data);
    }



    println(JSON.stringify(source));
    pushMessage("打包下载", "*正在压缩", currentUserId());
    var ret = createZipFileWith(p.fileName, source, watermark);
    println(JSON.stringify(ret));
    return ret;

}


id: 613fce31993240476a10bbc7
scriptid: 60a31c475db27838e0c01344
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:19:23.000
script:
function saveLabel(data) {
    println(data.length);
    println("=====");
    println(JSON.stringify(data));

    var labels={};
    var dzpz_pz_ds = newDataStore("", "select * from dzpz_pz");
    dzpz_pz_ds.setUpdateProperty("dzpz_pz", "id", "*", "id");

    for (var i = 0; i < data.length; i++) {
        var one = data[i];

        var ym = one['记帐期'];
        var pzh = one['凭证号'];
        println(pzh);
        dzpz_pz_ds.retrieve(" corporationid='" + currentUserCorporationId() + "' and  ym=" + ym + " and pzh='" + pzh + "'");
        var t = dzpz_pz_ds.getString(0, "labeldata");
        var id = dzpz_pz_ds.getString(0, "id");
        try {
            if (t != '') {
                t = JSON.parse(t);
            } else { t = {}; }
        } catch (err) {
            t = {};
        }
        println(typeof (t));
        if (typeof (t) != 'object') t = {};

        for (var p in one) {
            if( labels[p]==undefined) labels[p]=1;//记录下标签名称 
            var v = one[p];
            t[p] = v;
        }

        t = JSON.stringify(t);
        runSQL("", "update dzpz_pz set  labeldata='" + t + "' where  corporationid='" + currentUserCorporationId() + "' and  ym=" + ym + " and pzh='" + pzh + "' and id='" + id + "'   ", true);

    }

    //最后再把标签名称保存一下
    runTask("保存标签名称" , { labels: Object.keys(labels) },10); //延时

}


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

}




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



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


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



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

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

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

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

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

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

}


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

}

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

}


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


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

    //排除掉回收站的图片
    var sql = "select * from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''  order by info1 asc, filename asc ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。
    ds.setOnceRetrieveCount(40);

    var n = ds.retrieve();

    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return { success: true, totalCount: ds.getDBRowCount(), data: ret };

}

function getTotalImageCount() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

    //排除掉回收站的图片
    var sql = "select count(*) as c from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''    ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。


    ds.retrieve();
    println(ds.getSelectLastRetrieved());

    return ds.getInt(0, "c");

}

//@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("", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='" + id + "'  order by groupname , info1 asc ");
    var n = ds.retrieve();
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }
    return ret;

}



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


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

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

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


}

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

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

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


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


function reorderImageFileIndex(imgs) {

}


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

 var sqls = ["update dzpz_dymx  set bz=null,pz_id= (select id from dzpz_pz where dzpz_pz.pzh= dzpz_dymx.pzh ) where gguid='" + gguid + "' ",
    "update dzpz_dymx  set bz='凭证号不存在' where  gguid='" + gguid + "' and not exists (select dzpz_pz.id from dzpz_pz where  dzpz_pz.pzh= dzpz_dymx.pzh )  "
    ];

    runSQL("", sqls, true);

}


id: 613fce7a993240476a10bc23
scriptid: 60d095db993254220bd8519f
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:28:33.000
script:
//后端导入excel数据包
function backend_importExcelData(excelData) {
    var ret = {
        'success': false,
        'message': ''
    }
    // return { success: false, message: excelData }
    var dsn = '';
    var masterTable = 'pzdj';
    var tableName = 'pzdjex';
    //ret.message="select id,userid,verifiername from pzdj where gguid='" + currentGUID() + "'";
    //return ret;

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

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

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


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

    var excelSheet = excelData;

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


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

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

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

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

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

    var RC = excelSheet.length;

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

    }
    //println(JSON.toString(data));

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

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



    var ds = newDataStore(dsn, "select * from " + tableName);
    ds.setUpdateProperty(tableName, "id", "*", "id");
    for (var i = 0; i < data.length; i++) {
        var row = ds.insertRow(99999);
        pushMessage("dr_info", "导入进度：" + (i + 1) + "/" + data.length, currentUserId());

        var rowData = data[i];
        for (var col in rowData) {
            var value = rowData[col];
            ds.setValue(row, col, value);
        }
        ds.setValue(row, "id", newGuid());
        ds.setValue(row, "gguid", gguid);
        ds.setValue(row, "userid", userid);
        ds.setValue(row, "username", username);
        ds.setValue(row, "lastmodifieddate", lastmodifieddate);
    }

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

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

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

    return ret;
}

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

}


id: 613fd0be993240476a10bc47
scriptid: 60ac750d5db2f5d22859c4c0
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:30:09.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println( arg); 
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pzfj.id 
    println( "id="+ id);

   
    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" id='"+ id+"' ");
    var pzid = dzpz_pzfj_ds.getString(0,"gguid");
    println( "select  verifierid  from dzpz_pz  where id='"+pzid+"' ");
    if( getIntFromSQL("select  verifierid  from dzpz_pz  where id='"+pzid+"' ")>0)
    {
        println("已审核，禁止删除附件");
     return { success:false, message:'凭证已审核，禁止删除'};
    }
    

    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");


    var row = dzpz_imgpool_fileupload_ds.insertRow(9999);

    cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row);

    //数据调整


    dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证

    dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
    dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
    dzpz_imgpool_fileupload_ds.setValue(row, "corporationid", null);

    //删除源
    //当 
    dzpz_pzfj_ds.deleteRow(0);

    //更新附件数量
    dzpz_pzfj_ds.executeAfterUpdate(" update dzpz_pz  set attachmentcount= (select count(*) from dzpz_pzfj where gguid='"+ pzid+"' ) -1  where id='"+ pzid+"' ");


    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(0, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


id: 613fd0be993240476a10bc53
scriptid: 60ac944d5db2f5d22859c6de
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:30:40.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pz.id 
    println("id=" + id);


    if (getIntFromSQL( "select  verifierid  from dzpz_pz  where id='" + id + "' ") > 0) return { success: false, message: '凭证已审核，禁止删除' };
    if (getIntFromSQL( "select  userid  from dzpz_pz  where id='" + id + "' ") != toString(currentUserId())) return { success: false, message: '您不是该凭证归档人，禁止删除' };


    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" gguid='" + id + "' "); //检索出所有图片


    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");

    var RC = dzpz_pzfj_ds.getRowCount();
    for (var i = RC - 1; i >= 0; i--) {

        var row = dzpz_imgpool_fileupload_ds.insertRow(9999);
        cloneRow(dzpz_pzfj_ds, i, dzpz_imgpool_fileupload_ds, row);

        //数据调整

        dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证
        dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
        dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
        dzpz_imgpool_fileupload_ds.setValue(row, "corporationid", null);
        //删除源
        dzpz_pzfj_ds.deleteRow(i);
    }

    //删除凭证
    dzpz_pzfj_ds.executeAfterUpdate(" delete from  dzpz_pz  where id='" + id + "' ");

    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, sr, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(sr, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


id: 613fd0be993240476a10bc61
scriptid: 60ab513d5db26b6db2c28aa6
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:31:21.000
script:
/*
归档处理
  1 生成凭证主记录
  2 生成凭证附件记录

   pzGroup = 
   [
       { pzh:'xx1' , pz:['id1','id2'...] , fj :['id1', 'id2'.....]} , 
       { pzh:'xx2' , pz:['id1','id2'...] , fj :['id1', 'id2'.....]} ...  
       
   ]
*/

function main(arg) {

    var p = JSON.parse(arg);
    println(p.rawdata);
    var corporationid = p.corporationid;
    var ym = p.ym;
    var pzGroup = p.pzGroup;  //pzGroup 的结构是 [   {pzh: '0001', imgID:'xxxx', fj:['xxxx', 'xxxxx'...] } , { ... } ] 

    //先校验，要么全部归档，要么全部放弃

    for (var i = 0; i < pzGroup.length; i++) {
        var pzh   =  pzGroup[i].pzh;
        //验重： 指定单位，指定年月，指定凭证号不能重复
        if(  getStringFromSQL( "select id from dzpz_pz where pzh='"+pzh+"' and corporationid='"+ corporationid+"' and ym="+ym )!='')
        {
            return {success:false, message:pzh+"凭证号已存在，不允许重复归档"};
        }       
    }


    for (var i = 0; i < pzGroup.length; i++) {
        ret = gd(corporationid, ym, pzGroup[i]);
        if (!ret.success) return ret;
    }

    return { success: true };

}


function gd(corporationid, ym, config) {
    var dzpz_pz_ds = newDataStore("", "select * from dzpz_pz ");  //凭证主记录
    dzpz_pz_ds.setUpdateProperty("dzpz_pz", "id", "*", "id");

    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");

    //用来检索数据
    var dzpz_imgpool_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");

    //用来更新数据
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");


    var id = newGUID();
    dzpz_pz_ds.insertRow(0);
    dzpz_pz_ds.setValue(0, "id", id);
    dzpz_pz_ds.setValue(0, "gguid", id);
    dzpz_pz_ds.setValue(0, "billno", id);
    dzpz_pz_ds.setValue(0, "billdate", newDate());
    dzpz_pz_ds.setValue(0, "billtype", "");
    dzpz_pz_ds.setValue(0, "open_bill_with_url", "billedit?action=view&gguid=" + id + "&id=dzpz");
    dzpz_pz_ds.setValue(0, "userid", currentUserId());
    dzpz_pz_ds.setValue(0, "username", currentUserShowName());
    dzpz_pz_ds.setValue(0, "pzh", config.pzh);
    dzpz_pz_ds.setValue(0, "attachmentcount", config.fj.length + config.pz.length); //凭证与附件的图片总和
    dzpz_pz_ds.setValue(0, "ym", ym);
    dzpz_pz_ds.setValue(0, "imgid", config.imgID);

    dzpz_pz_ds.setValue(0, "corporationid", corporationid);
    dzpz_pz_ds.setValue(0, "deleteflag", 0);

    // 附件清单

    var FJGD = function (imgs, groupName) {
        for (var i = 0; i < imgs.length; i++) {
            var fromID = imgs[i];

            dzpz_imgpool_ds.retrieve(" id='" + fromID + "'");
            if (dzpz_imgpool_ds.getRowCount() != 1) {
                println(config.fj[i] + " 对应的上传记录不存在")
                continue;
            }

            var row = dzpz_pzfj_ds.insertRow(9999);

            cloneRow(dzpz_imgpool_ds, dzpz_pzfj_ds, row);

            //数据调整



            //附件表上的附件类型
            dzpz_pzfj_ds.setValue(row, "groupname", groupName);  //把类型改成 凭证

            dzpz_pzfj_ds.setValue(row, "fileindex", i + 1);

            dzpz_pzfj_ds.setValue(row, "gguid", id);
            dzpz_pzfj_ds.setValue(row, "tablename", "dzpz_pz");
            dzpz_pzfj_ds.setValue(row, "corporationid", corporationid);

            //删除源
            //当 
            dzpz_imgpool_fileupload_ds.executeAfterUpdate(" delete from dzpz_imgpool_fileupload where id='" + fromID + "' ");

        }
    }

    FJGD( config.pz , '凭证' ); //凭证
    FJGD( config.fj , '附件' ); //附件
    
    dzpz_pz_ds.setValue(0,"pz", config.pz.length);//凭证张数
    dzpz_pz_ds.setValue(0,"fj", config.fj.length);//附件张数
    

    var err = '' + updateAll(dzpz_pz_ds, dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_imgpool_ds, dzpz_pzfj_ds, row) {
    for (var i = 0; i < dzpz_imgpool_ds.getColumnCount(); i++) {
        var col = dzpz_imgpool_ds.getColumnName(i);
        var value = dzpz_imgpool_ds.getValue(0, i);
        dzpz_pzfj_ds.setValue(row, col, value);
    }
}


id: 613fd0be993240476a10bc6d
scriptid: 60ac8be75db2f5d22859c588
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:31:46.000
script:
/*

   凭证主记录已存在 ， 向凭证中添加更多的附件
   

*/

function main(arg)
{
   
    var p= JSON.parse(arg);
    println( p.rawdata);
    var id= p.pzid;
    var images= p.images;


    var  dzpz_pz_ds = newDataStore("", "select * from dzpz_pz ");  //凭证主记录
    dzpz_pz_ds.retrieve(" id='"+  id+"' ");

    var  dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id","*" ,"id");

    //用来检索数据
    var  dzpz_imgpool_ds= newDataStore("","select * from dzpz_imgpool_fileupload");

    //用来更新数据
    var  dzpz_imgpool_fileupload_ds= newDataStore("","select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id","*" ,"id");
    
 
    var corporationid= dzpz_pz_ds.getValue(0,"corporationid");
     
    // 附件清单
    for( var i=0;i< images.length;i++)
    {
        var fromID = images[i].id;
        
        dzpz_imgpool_ds.retrieve(" id='"+fromID+"'");
        if( dzpz_imgpool_ds.getRowCount()!=1)
        {
            println( config.fj[i]+" 对应的上传记录不存在")
            continue; 
        }

        var row= dzpz_pzfj_ds.insertRow(9999);

        cloneRow( dzpz_imgpool_ds , dzpz_pzfj_ds , row);

        //数据调整
  
        dzpz_pzfj_ds.setValue(row,"gguid", id);
        dzpz_pzfj_ds.setValue(row,"tablename", "dzpz_pz");
        dzpz_pzfj_ds.setValue(row,"corporationid", corporationid);

        //删除源
        //当 
        dzpz_imgpool_fileupload_ds.executeAfterUpdate( " delete from dzpz_imgpool_fileupload where id='"+fromID+"' ");

        
    }

    //更新凭证附件数量
    dzpz_pzfj_ds.executeAfterUpdate(" update dzpz_pz  set attachmentcount= (select count(*) from dzpz_pzfj where gguid='"+ id+"' ) -1  where id='"+ id+"' ");

    var err =  ''+updateAll( dzpz_pzfj_ds ,dzpz_imgpool_fileupload_ds);

    if( err=='') return  {success:true};
    println( err);
    return {success:false, message:err}; 

}

function cloneRow( dzpz_imgpool_ds , dzpz_pzfj_ds , row)
{
    for( var i=0;i<dzpz_imgpool_ds.getColumnCount();i++)
    {
        var col= dzpz_imgpool_ds.getColumnName(i);
        var value= dzpz_imgpool_ds.getValue(0 , i);
        dzpz_pzfj_ds.setValue(row, col , value);  
    }
}


id: 613fd0be993240476a10bc81
scriptid: 60ab2c0d5db2f37491f9970b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 06:32:55.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    var corporationid= p.corporationid;
    var ym= p.ym;
    var ds=newDataStore("", "select * from dzpz_gz");
    ds.setUpdateProperty("dzpz_gz","id","*","id");
    ds.retrieve(" corporationid='"+ corporationid+"'  and ym="+ ym);
    if( ds.getRowCount()==0)
    {
        ds.insertRow(0);
        var newid= newGUID();
        ds.setValue(0,"id", newid);
        ds.setValue(0,"gguid", newid);
        ds.setValue(0,"billno", newid);
        ds.setValue(0,"billdate", newDate());
        ds.setValue(0,"userid", currentUserId());
        ds.setValue(0,"username", currentUserShowName());
        ds.setValue(0,"corporationid", corporationid);
        ds.setValue(0,"ym", ym);
        
    }

    ds.setValue(0,"state", 0);
    ds.setValue(0,"gzsj", null); //关帐时间 
    
    if( ds.update(true)) return {success:true};
    var err= ds.getError().getMessage();
    println( err);
    return {success:false, message:err};

}


id: 613fdd5d993240476a10daaf
scriptid: 60a31c3c5db27838e0c012a2
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 07:23:09.000
script:
var labelDataInited=false;

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


}

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

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


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

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


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


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

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


id: 613fded0993240476a10db84
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 13:32:15.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corporationid = sheet.cells("corporationid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corporationid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 613fded0993240476a10db8a
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 13:33:14.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:gray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 613fded0993240476a10db90
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 13:34:07.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:lightgray;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 613fded0993240476a10db96
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 13:34:39.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 613fded0993240476a10db9c
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:03:34.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 61403c23993240476a10dbe8
scriptid: 60a31c475db27838e0c01348
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:09:21.000
script:
/**
 * 表单初始化完成后，执行此事件
 */
//@comment (group=表单事件,caption=表单初始化完成)
function formOpen() {
    book.showTabOnWhere = 'none';
}

function cb_import_onClick() {



    book.readXLS(function (data) {
        importData(data);
    });
}


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

}

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

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


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

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

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

        excelColIndex2ColName['' + i] = v;
        excelColName2ColIndex[v] = '' + i;
    }
    console.info(JSON.stringify(excelColName2ColIndex));
    console.info(JSON.stringify(excelColIndex2ColName));



    var RC = excelSheet.length;

    var data = [];
    for (var row = dataStartRow; row < RC; row++) {
        var oneRowData = {};
        data.push(oneRowData);
        for (var label in excelColName2ColIndex) {
            var excelCol = excelColName2ColIndex[label];

            oneRowData[label] = safeValue(excelSheet, row, excelCol);

        }

    }

    console.dir(data);
    showInfoPane('*正在导入标签');
    saveLabel( book.sheet0.cells('corpid').getValueString() , data, function (ret) {
        hideInfoPane();
        toastr.info("导入完成");
    });


}


id: 61403c23993240476a10dc09
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:13:14.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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


    });

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


}

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

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


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

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

    }
}

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

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

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

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

    


}

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

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


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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}



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

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

    }

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

}

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

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

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

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

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


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

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



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

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

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


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



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


    });
}



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



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


    });
}


function cb_package_onClick() {

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

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

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

    });
}


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

}

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

}


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


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

    //排除掉回收站的图片
    var sql = "select * from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''  order by info1 asc, filename asc ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。
    ds.setOnceRetrieveCount(40);

    var n = ds.retrieve();

    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return { success: true, totalCount: ds.getDBRowCount(), data: ret };

}

function getTotalImageCount() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

    //排除掉回收站的图片
    var sql = "select count(*) as c from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''    ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。


    ds.retrieve();
    println(ds.getSelectLastRetrieved());

    return ds.getInt(0, "c");

}

//@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("", "select id , url_img , url_thumbnail ,groupname , info1 from  dzpz_pzfj where  gguid='" + id + "'  order by groupname , info1 asc ");
    var n = ds.retrieve();
    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }
    return ret;

}



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


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

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

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


}

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

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

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


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


function reorderImageFileIndex(imgs) {

}


id: 61403de4993240476a10dcfe
scriptid: 60ac750d5db2f5d22859c4c0
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:49:23.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println( arg); 
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pzfj.id 
    println( "id="+ id);

   
    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" id='"+ id+"' ");
    var pzid = dzpz_pzfj_ds.getString(0,"gguid");
    println( "select  verifierid  from dzpz_pz  where id='"+pzid+"' ");
    if( getIntFromSQL("select  verifierid  from dzpz_pz  where id='"+pzid+"' ")>0)
    {
        println("已审核，禁止删除附件");
     return { success:false, message:'凭证已审核，禁止删除'};
    }
    

    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");


    var row = dzpz_imgpool_fileupload_ds.insertRow(9999);

    cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row);

    //数据调整


    dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证

    dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
    dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
    dzpz_imgpool_fileupload_ds.setValue(row, "corpid", null);

    //删除源
    //当 
    dzpz_pzfj_ds.deleteRow(0);

    //更新附件数量
    dzpz_pzfj_ds.executeAfterUpdate(" update dzpz_pz  set attachmentcount= (select count(*) from dzpz_pzfj where gguid='"+ pzid+"' ) -1  where id='"+ pzid+"' ");


    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(0, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


id: 61404605993240476a10dd06
scriptid: 60ac750d5db2f5d22859c4c0
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:49:42.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println( arg); 
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pzfj.id 
    println( "id="+ id);

   
    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" id='"+ id+"' ");
    var pzid = dzpz_pzfj_ds.getString(0,"gguid");
    println( "select  verifierid  from dzpz_pz  where id='"+pzid+"' ");
    if( getIntFromSQL("select  verifierid  from dzpz_pz  where id='"+pzid+"' ")>0)
    {
        println("已审核，禁止删除附件");
     return { success:false, message:'凭证已审核，禁止删除'};
    }
    

    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");


    var row = dzpz_imgpool_fileupload_ds.insertRow(9999);

    cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row);

    //数据调整


    dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证

    dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
    dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
   // dzpz_imgpool_fileupload_ds.setValue(row, "corpid", null);

    //删除源
    //当 
    dzpz_pzfj_ds.deleteRow(0);

    //更新附件数量
    dzpz_pzfj_ds.executeAfterUpdate(" update dzpz_pz  set attachmentcount= (select count(*) from dzpz_pzfj where gguid='"+ pzid+"' ) -1  where id='"+ pzid+"' ");


    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(0, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


id: 61404605993240476a10dd12
scriptid: 60ac944d5db2f5d22859c6de
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:50:00.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pz.id 
    println("id=" + id);


    if (getIntFromSQL( "select  verifierid  from dzpz_pz  where id='" + id + "' ") > 0) return { success: false, message: '凭证已审核，禁止删除' };
    if (getIntFromSQL( "select  userid  from dzpz_pz  where id='" + id + "' ") != toString(currentUserId())) return { success: false, message: '您不是该凭证归档人，禁止删除' };


    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" gguid='" + id + "' "); //检索出所有图片


    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");

    var RC = dzpz_pzfj_ds.getRowCount();
    for (var i = RC - 1; i >= 0; i--) {

        var row = dzpz_imgpool_fileupload_ds.insertRow(9999);
        cloneRow(dzpz_pzfj_ds, i, dzpz_imgpool_fileupload_ds, row);

        //数据调整

        dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证
        dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
        dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
       // dzpz_imgpool_fileupload_ds.setValue(row, "corporationid", null);
        //删除源
        dzpz_pzfj_ds.deleteRow(i);
    }

    //删除凭证
    dzpz_pzfj_ds.executeAfterUpdate(" delete from  dzpz_pz  where id='" + id + "' ");

    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, sr, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(sr, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


id: 61404605993240476a10dd1e
scriptid: 60ac8be75db2f5d22859c588
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:50:38.000
script:
/*

   凭证主记录已存在 ， 向凭证中添加更多的附件
   

*/

function main(arg)
{
   
    var p= JSON.parse(arg);
    println( p.rawdata);
    var id= p.pzid;
    var images= p.images;


    var  dzpz_pz_ds = newDataStore("", "select * from dzpz_pz ");  //凭证主记录
    dzpz_pz_ds.retrieve(" id='"+  id+"' ");

    var  dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id","*" ,"id");

    //用来检索数据
    var  dzpz_imgpool_ds= newDataStore("","select * from dzpz_imgpool_fileupload");

    //用来更新数据
    var  dzpz_imgpool_fileupload_ds= newDataStore("","select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id","*" ,"id");
    
 
    var corpid= dzpz_pz_ds.getValue(0,"corpid");
     
    // 附件清单
    for( var i=0;i< images.length;i++)
    {
        var fromID = images[i].id;
        
        dzpz_imgpool_ds.retrieve(" id='"+fromID+"'");
        if( dzpz_imgpool_ds.getRowCount()!=1)
        {
            println( config.fj[i]+" 对应的上传记录不存在")
            continue; 
        }

        var row= dzpz_pzfj_ds.insertRow(9999);

        cloneRow( dzpz_imgpool_ds , dzpz_pzfj_ds , row);

        //数据调整
  
        dzpz_pzfj_ds.setValue(row,"gguid", id);
        dzpz_pzfj_ds.setValue(row,"tablename", "dzpz_pz");
        dzpz_pzfj_ds.setValue(row,"corpid", corpid);

        //删除源
        //当 
        dzpz_imgpool_fileupload_ds.executeAfterUpdate( " delete from dzpz_imgpool_fileupload where id='"+fromID+"' ");

        
    }

    //更新凭证附件数量
    dzpz_pzfj_ds.executeAfterUpdate(" update dzpz_pz  set attachmentcount= (select count(*) from dzpz_pzfj where gguid='"+ id+"' ) -1  where id='"+ id+"' ");

    var err =  ''+updateAll( dzpz_pzfj_ds ,dzpz_imgpool_fileupload_ds);

    if( err=='') return  {success:true};
    println( err);
    return {success:false, message:err}; 

}

function cloneRow( dzpz_imgpool_ds , dzpz_pzfj_ds , row)
{
    for( var i=0;i<dzpz_imgpool_ds.getColumnCount();i++)
    {
        var col= dzpz_imgpool_ds.getColumnName(i);
        var value= dzpz_imgpool_ds.getValue(0 , i);
        dzpz_pzfj_ds.setValue(row, col , value);  
    }
}


id: 61404605993240476a10dd2a
scriptid: 60ac944d5db2f5d22859c6de
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 14:50:58.000
script:
/*
凭证中的某个附件移除，并还原到待归档图片池中
  1 记录移除
  2 移到 待归档图片池中
  3  几个标记数据还愿

*/

function main(arg) {

    println(arg);
    var p = JSON.parse(arg);
    var id = p.id;  // dzpz_pz.id 
    println("id=" + id);


    if (getIntFromSQL( "select  verifierid  from dzpz_pz  where id='" + id + "' ") > 0) return { success: false, message: '凭证已审核，禁止删除' };
    if (getIntFromSQL( "select  userid  from dzpz_pz  where id='" + id + "' ") != toString(currentUserId())) return { success: false, message: '您不是该凭证归档人，禁止删除' };


    //得到当前操作员待归档图片对应的GGUID
    var t = runTask("get_dzpz_imgpool_id_of_current_user", {});
    var gguid = JSON.parse(t).gguid;


    var dzpz_pzfj_ds = newDataStore("", "select * from dzpz_pzfj "); //凭证附件
    dzpz_pzfj_ds.setUpdateProperty("dzpz_pzfj", "id", "*", "id");
    dzpz_pzfj_ds.retrieve(" gguid='" + id + "' "); //检索出所有图片


    //待归档的图片池
    var dzpz_imgpool_fileupload_ds = newDataStore("", "select * from dzpz_imgpool_fileupload");
    dzpz_imgpool_fileupload_ds.setUpdateProperty("dzpz_imgpool_fileupload", "id", "*", "id");

    var RC = dzpz_pzfj_ds.getRowCount();
    for (var i = RC - 1; i >= 0; i--) {

        var row = dzpz_imgpool_fileupload_ds.insertRow(9999);
        cloneRow(dzpz_pzfj_ds, i, dzpz_imgpool_fileupload_ds, row);

        //数据调整

        dzpz_imgpool_fileupload_ds.setValue(row, "groupname", '附件');  //把类型改成 凭证
        dzpz_imgpool_fileupload_ds.setValue(row, "gguid", gguid);
        dzpz_imgpool_fileupload_ds.setValue(row, "tablename", "dzpz_imgpool");
        dzpz_imgpool_fileupload_ds.setValue(row, "corpid", null);
        //删除源
        dzpz_pzfj_ds.deleteRow(i);
    }

    //删除凭证
    dzpz_pzfj_ds.executeAfterUpdate(" delete from  dzpz_pz  where id='" + id + "' ");

    var err = '' + updateAll(dzpz_pzfj_ds, dzpz_imgpool_fileupload_ds);

    if (err == '') return { success: true };
    println(err);
    return { success: false, message: err };

}

function cloneRow(dzpz_pzfj_ds, sr, dzpz_imgpool_fileupload_ds, row) {
    for (var i = 0; i < dzpz_pzfj_ds.getColumnCount(); i++) {
        var col = dzpz_pzfj_ds.getColumnName(i);
        var value = dzpz_pzfj_ds.getValue(sr, i);
        dzpz_imgpool_fileupload_ds.setValue(row, col, value);
    }
}


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

}




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



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


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



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

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

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

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

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

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

}


id: 61404c14993240476a10dfbb
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 15:23:36.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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


    });

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


}

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

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


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

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

    }
}

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

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

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

    


}

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

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


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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}



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

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

    }

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

}

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

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

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

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

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


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

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



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

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

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


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



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


    });
}



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



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


    });
}


function cb_package_onClick() {

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

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

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

    });
}


id: 61404eef993240476a10dfc5
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 15:27:43.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

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

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

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


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


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

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

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

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

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


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

            fullScreenViewImageClose();

        }
    });

}


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

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

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

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

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




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

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

}

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

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

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

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

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

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



}

function resetImageCountInfo() {

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

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


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

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


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

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

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

                    }
                }, 10);
            }
        );

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

    }
}


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

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

        }
    }

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


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

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


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

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

    }


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

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

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

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

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

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

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


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

    if (showDlg == undefined) showDlg = true;

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

    }, 200);

    var pzh = '';
    try {

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

    }

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

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


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

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

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

    if (needDeleteButton == undefined) needDeleteButton = true;

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

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

}

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

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

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


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

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

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

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

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

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

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

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

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



}

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

}

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


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

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

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

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

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

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

            if (ret.success) {

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

        });
}

function setButtonsStatus(b) {

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

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

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


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

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

}



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

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


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

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen();
            pzh_prefix = getPZHPrefix(ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


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

}

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

}


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


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

    //排除掉回收站的图片
    var sql = "select * from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''  order by info1 asc, filename asc ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。
    ds.setOnceRetrieveCount(40);

    var n = ds.retrieve();

    var ret = [];
    for (var i = 0; i < n; i++) {
        ret.push(JSON.parse(ds.getJSONRow(i, true)));
    }

    return { success: true, totalCount: ds.getDBRowCount(), data: ret };

}

function getTotalImageCount() {
    var config = JSON.parse(runTask("get_dzpz_imgpool_id_of_current_user", {}));

    //排除掉回收站的图片
    var sql = "select count(*) as c from " + config.logTable + "  where  gguid='" + config.gguid +
        "'  and ifnull(info2,'')=''    ";
    println(sql);
    var ds = newDataStore(config.dbpool, sql); // info1 是客户端文件创建的时间，以它排序厅。


    ds.retrieve();
    println(ds.getSelectLastRetrieved());

    return ds.getInt(0, "c");

}

//@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("", "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(corpid,ym) {
    return runTask("getPZHPrefix", { ym: ym ,corpid:corpid });

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

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


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


function reorderImageFileIndex(imgs) {

}


id: 61404eef993240476a10dffd
scriptid: 60c9fca09932d177d8ac61aa
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 15:35:34.000
script:
function main(arg)
{
    var p= JSON.parse(arg);
    var corpid= p.corpid;
    var ym= ''+ p.ym;
    var y= ym.substring(0,4);
    var m= ym.substring(4,6);

    var t =  getStringFromSQL(" select pzh_prefix  from basic_corp where code='"+ corpid+"' ")
    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  );

    var m2= ''+ parseInt(m); // 把 01 转成 1 
    if( t.indexOf("{m}")>=0)  t=t.replace(/[{]m[}]/g , m2  );  // 1-9月直接用数字 ，而不要补0 
    
    return t; 
}


id: 61405102993240476a10e02f
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 15:40:09.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

    //加载帐套信息及年月
    var corpid = book.sheet2.cells("corpid").getValueString();
      book.sheet2.cells("ym").setValue(ym);
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen(corpid);
        pzh_prefix = getPZHPrefix(corpid , ym);

        getLastPZH(corpid, ym, function (v) {
            if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8);
            lastPZH = v;
        });

    // smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    // });

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}


// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("前 " + book.sheet1.getBrick("imgPool").imageCount + " 张");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "pzh"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

/**
 * 图片控件中某个图片被单击
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 * @param event  事件对象
 *
 *
 */
//@comment (group=图片控件,caption=图片被单击)
function imageOnClick(sheet, name, data, event) {

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event, showDlg) {

    if (showDlg == undefined) showDlg = true;

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corpid: book.sheet4.cells("corpid").getValueString(),
            ym: book.sheet4.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}



function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen(corpid);
            pzh_prefix = getPZHPrefix(corpid, ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 61405102993240476a10e035
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 15:50:43.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corpid = book.sheet2.cells("corpid").getValueString();
    var ym= book.sheet2.cells("ym").getValue( );
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen(corpid);
        pzh_prefix = getPZHPrefix(corpid , ym);

        getLastPZH(corpid, ym, function (v) {
            if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8);
            lastPZH = v;
        });

    // smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    // });

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}


// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("前 " + book.sheet1.getBrick("imgPool").imageCount + " 张");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "pzh"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

/**
 * 图片控件中某个图片被单击
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 * @param event  事件对象
 *
 *
 */
//@comment (group=图片控件,caption=图片被单击)
function imageOnClick(sheet, name, data, event) {

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event, showDlg) {

    if (showDlg == undefined) showDlg = true;

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corpid: book.sheet4.cells("corpid").getValueString(),
            ym: book.sheet4.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}



function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
            //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            // book.sheet2.cells("ym").setValue(ym);
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen(corpid);
            pzh_prefix = getPZHPrefix(corpid, ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
                // alert(lastPZH);
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
        };
    }

}


id: 61405d1f993240476a10e08e
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 16:28:16.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corpid = book.sheet2.cells("corpid").getValueString();
    var ym= book.sheet2.cells("ym").getValue( );
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen(corpid);
        pzh_prefix = getPZHPrefix(corpid , ym);

        getLastPZH(corpid, ym, function (v) {
            if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8);
            lastPZH = v;
        });

    // smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    // });

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}


// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("前 " + book.sheet1.getBrick("imgPool").imageCount + " 张");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "pzh"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

/**
 * 图片控件中某个图片被单击
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 * @param event  事件对象
 *
 *
 */
//@comment (group=图片控件,caption=图片被单击)
function imageOnClick(sheet, name, data, event) {

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event, showDlg) {

    if (showDlg == undefined) showDlg = true;

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corpid: book.sheet4.cells("corpid").getValueString(),
            ym: book.sheet4.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
            smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}



function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
           reload_pzh_info();
        };
    }

}


function reload_pzh_info()
{
    var sheet=book.getWorkSheet ('凭证清单') ;
     //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen(corpid);
            pzh_prefix = getPZHPrefix(corpid, ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
              
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
}


id: 61405d1f993240476a10e094
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.09.14 16:29:20.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

/*
$(document).ready(function () {
    var script = $(`<script src="ui/imageEditor/filerobot-image-editor.min.js">
    
    </script>`);
    $(document.body).append(script);
});
*/

function formOpen() {

    book.sheet4.visible = false;

    book.showTabOnWhere = "none";
    newImgCommingTipVisible(false);

    book.sheet3.getBrick('cb_delete_pz').visible = false;

    //加载帐套信息及年月
    var corpid = book.sheet2.cells("corpid").getValueString();
    var ym= book.sheet2.cells("ym").getValue( );
        //得到年月后，获取凭证号相关设置
        pzh_len = getPZHLen(corpid);
        pzh_prefix = getPZHPrefix(corpid , ym);

        getLastPZH(corpid, ym, function (v) {
            if (v == '') v = pzh_prefix + '00000001'.substring(8 - pzh_len, 8);
            lastPZH = v;
        });

    // smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
    // });

    book.getWorkSheet('凭证清单').cells("yue").setValue(  getMonth(newDate()));

    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:30px; line-height:30px;width:100%; 
                                background-color:#af4040e0; 
                                color:white;font-weight:bold;font-size:20px;text-align:left;}
                        .delete_pzh { position:absolute; right:0; width:40px; height:44px; top:0; text-align:right; 
                                    vertical-align:top; font-size:24px; color:#ffa0a0;padding-right:5px;}      
                        .delete_pzh:hover { color:white;}      
                          
                        </style>
                    `);


    //注册调整缩略图大小的事件
    $('#blockSize').on('input', resetImgPoolBlockSize);


    setTimeout(function () {
        //调取缩略图大小

        var imgPool = book.sheet1.getBrick('imgPool');
        let blockSize = getImagePoolBlockSize();
        if (blockSize != imgPool.config.blockSize) {
            $('#blockSize').val(blockSize);
            resetImgPoolBlockSize(false);
        }
    }, 1000);

    //调取图片目录设置，注意适当延时
    setTimeout(function () {
        if (electron != null) {
            var hostName = electron.getHostName();
            pathToMonit = getMonitePath(hostName);

            //开启监控
            if (pathToMonit == '') pathToMonit = "c:\\凭证影像采集目录";

            moniteStart(pathToMonit);
            $.alert('请将扫描仪的图片目录指向：' + pathToMonit);
        }

        //显示总共图片数
    getTotalImageCount( function(ret){ book.sheet0.cells('imageCountTotal').setValue('共'+ret+'张')});

    }, 500);

    

    $(document).on('keydown', function (e) {
        console.info(" kkkkk down");
        if (e.ctrlKey) {
            fullScreenViewImageOpen();
        }
    });


    $(document).on('keyup', function (e) {
        console.info(" kkkkk up");
        if (!e.ctrlKey) {

            fullScreenViewImageClose();

        }
    });

}


// 先保存当前选中状态及设置的凭证号信息

var g_selection;
var g_pzMap;
//@comment (group=图片清单刷新,caption=保存选中状态及凭证标记信息,needRightControl=false)
function saveSelectionAndPZInfo() {

    var imgPool = book.sheet1.getBrick('imgPool');

    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    // 保存设置的凭证号信息
    var pzhMap = {};
    var pzhs = imgPool.dom.find('.pzh');
    for (let i = 0; i < pzhs.length; i++) {
        let id = $(pzhs[i]).parent().attr('id');
        let pzh = $(pzhs[i]).find('.no').text();
        pzhMap[id] = pzh;

    }
    g_selection = selection;
    g_pzMap = pzhMap;
}




//@comment (group=图片清单刷新,caption=还原选中及凭证标记,needRightControl=false)
function restoreSelectionAndPZInfo() {
    var selection = g_selection;
    var pzhMap = g_pzMap;
    var imgPool = book.sheet1.getBrick('imgPool');

    //恢复选中状态
    for (let i = 0; i < selection.length; i++) {
        imgPool.setImageSelected(selection[i].id, true);
    }
    //恢复凭证号
    for (let id in pzhMap) {
        var pzh = pzhMap[id];
        find_pzh(id, true).find('.no').text(pzh);
    }

}

//@comment (group=图片控件,caption=重设小图大小,needRightControl=false)
function resetImgPoolBlockSize(needSaveSetting) {
    if (needSaveSetting == null) needSaveSetting = true;
    var imgPool = book.sheet1.getBrick('imgPool');

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    let v = $('#blockSize').val();

    imgPool.config.blockSize = parseInt(v);
    imgPool.rebuildGridly();

    //恢复选中状态
    restoreSelectionAndPZInfo();

    if (needSaveSetting) {
        setTimeout(function () {
            setImagePoolBlockSize(imgPool.getConfig("gguid"), v);
        }, 1000);
    }



}

function resetImageCountInfo() {

    setTimeout(function () {
        book.sheet0.cells("imageCount").setValue("前 " + book.sheet1.getBrick("imgPool").imageCount + " 张");
    }, 300);
}

/**
 * 图片控件初始化完成
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片控件初始化完成)
function imageGridlyInited(sheet, name, data) {


    if (name == "imgPool") {
        resetImageCountInfo()
        //图片都初始化后， 定制右上角的工具栏，最多可加5个工具按 钮
        let brick = sheet.getBrick(name);

        book.sheet0.cells("imageCount").setValue(brick.imageCout + "张图片");


        brick.addToolButton(2  //在从右往左数第2个工作栏位置添加一个工具按钮
            , "fa-repeat",   // 字符图标
            "旋转图片",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {  //点击后的回调函数

                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, "90");
                    if (ret.success) {
                        //把数据中的图片替换，
                        for (let i = 0; i < brick.data.length; i++) {
                            if (brick.data[i].id == id) {
                                //属性从新的属性中替换 
                                for (let prop in brick.data[i]) {
                                    brick.data[i][prop] = ret.data[prop];
                                }
                                break;
                            }
                        }
                        //把缩略图的图片地址替换 ， 

                        let img = $('#' + id).find('.image');
                        img.attr("src", ret.data.url_thumbnail);
                        img.attr('largeimage', ret.data.url_img);
                        //把大图预览的地址替换掉
                        book.sheet0.cells("imgPreview").setValue(ret.data.url_img);
                        hideInfoPane();

                    }
                }, 10);
            }
        );

        /* 
                brick.addToolButton(3  //在从右往左数第2个工作栏位置添加一个工具按钮
                    , "fa-crop",   // 字符图标
                    "旋转图片",  // 鼠标悬停的提示信息
                    "green", //按钮背景色
                    function (id) { 
                        let img = $('#' + id).find('.image');
                        let url= getServiceHomeURL('app')+ '/'+img.attr("largeimage");
                         console.info( url);
                         url="https://www.baidu.com/img/flexible/logo/pc/result.png";
                        const ImageEditor = new FilerobotImageEditor();
                        ImageEditor.open( url );
                    });
         */

    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 * @param data  图片的信息
 *
 * @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行删除操作，否则表示终止删除操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上的删除按钮被点击)
function imageOnDelete(sheet, name, data) {

    if (name == 'FJ') {
        if (data.groupname == '凭证') {
            return { success: false, message: "这是凭证，不允许这样移除，请点击“删除凭证”" };
        } else {
            var ret = putImageBackToPool(data.id);
            if (ret.success) {
                smartRetrieve(book.sheet3, "one");
                cb_refresh_onClick();
            } else {
                return ret;
            }

        }
    }

    if (name == 'imgPool') {
        moveImageToRecycle(data.id);
        resetImageCountInfo();
    }
    return { success: true };
}
/**
 * 图片控件中上传按钮被点击
 * @param sheet   所在Sheet
 * @param name  图片控件的名称
 *
 @returns  {object}    返回一个对象 ， 其中  success= boolean 表示继续执行上传操作，否则表示终止上传操作
 *    如果需要显示一个提示信息，则在 属性 message 中指定
 */
//@comment (group=图片控件,caption=图片上传按钮被点击)
function imageOnNewUpload(sheet, name) {


    if (name == 'imgPool') {
        toastr.info("请连接扫描仪，或将图片复制到监控的目录下，图片自动上传");
    }

    if (name == 'FJ') {
        var imgPool = book.sheet1.getBrick('imgPool');
        // 保存当前选中状态及设置的凭证号信息
        var selection = imgPool.getSelectedImageList();
        if (selection.length == 0) {
            toastr.error("至少选中一张图片");
            return { success: false }; // 此返回，阻止了默认的上传操作
        }


        var lastPZ = null;
        for (let i = 0; i < selection.length; i++) {
            var one = selection[i];
            var pzh = getPZH(one.id);
            if (pzh != '') {
                toastr.error("选中的图片中有标记为凭证的，禁止将凭证图片添加到当前凭证中");
                return { success: false }; // 此返回，阻止了默认的上传操作
            }
        }

        var ret = addImageToPZ($one_ds.getString(0, "id"), selection);
        if (ret.success) {
            //刷新图片区
            cb_refresh_onClick();
            //刷新凭证
            loadPZ($one_ds.getString(0, "id"), $one_ds.getString(0, "pzh"), $one_ds.getString(0, "verifiername") != "" ? 1 : 0);
        }

    }


    return { success: false }; // 此返回，阻止了默认的上传操作
}

//先定位 Id的序号， 然后返回它左边的图片的ID
function findLeftImageId(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    if (index > 0) return imgs[index - 1].id;
    return "";
}


//找到左边最近的一张凭证号
//如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
//否则在那个号上加1做为自已的凭证号
function incLeftNearestPZH(id) {
    let imgPool = book.sheet1.getBrick("imgPool");
    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    //找到自已的索引号
    let index = 0;
    for (let i = 0; i < imgs.length; i++) {
        if (imgs[i].id == id) {
            index = i;
            break;
        }
    }

    //再从index往左边查到第一张凭证
    for (let i = index - 1; i >= 0; i--) {
        let tid = imgs[i].id;
        let pzh = getPZH(tid);
        if (pzh == '') continue;
        if (i == index - 1) {
            return pzh; // 左边最近的一张凭证号就在自已的左边，那么就意味着自已与左边那张凭证号可能就是一张凭证的不同分页，所以直接返回凭证号
        } else {
            return stringInc(pzh);
        }

    }
    //到这里，都没有找到凭证号，那么直接返回凭证号前缀
    return stringInc(lastPZH);
}

/**
 * 图片控件中鼠标进入某个图片区域
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=鼠标进入图片区域)
function imageOnMouseEnter(sheet, name, data, event) {
    //console.dir(data);
    var url = data.url_img;
    book.sheet0.cells("imgPreview").setValue(url);
}
//@comment (group=图片控件,caption=鼠标从图片移开,needRightControl=false)
function imageOnMouseOut(sheet, name, data, event) {

    // book.sheet0.cells("imgPreview").setValue("");
}

/**
 * 图片控件中图片顺序变化了
 * @param sheet   所在Sheet
 * @param config  图片控件的配置信息
 *@param ids  调整顺序后的id清单
 *
 */
//@comment (group=图片控件,caption=顺序调整后)
function attachmentOrderChanged(sheet , config, ids ) {

    
     let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
     reorderImageFileIndex( imgs);

}

/**
 * 图片控件中某个图片被单击
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 * @param event  事件对象
 *
 *
 */
//@comment (group=图片控件,caption=图片被单击)
function imageOnClick(sheet, name, data, event) {

    if (name == 'imgPool') {
        if (book.sheet0.cells("clickAction").getValue() == 2) imageOnDBLClick(sheet, name, data, event, false);
    }
}


var g_lastPZH = "";
/**
 * 图片控件中某个图片被双击了
 * @param sheet   所在Sheet
 * @param config  图片控件的名称
 *@param data  该图片的详细信息
 *
 */
//@comment (group=图片控件,caption=图片被双击)
function imageOnDBLClick(sheet, name, data, event, showDlg) {

    if (showDlg == undefined) showDlg = true;

    //因为 mouseOut 会把大图清除掉，所以这里重新再设置上
    setTimeout(function () {
        var url = data.url_img;
        book.sheet0.cells("imgPreview").setValue(url);

    }, 200);

    var pzh = '';
    try {

        pzh = find_pzh(data.id, false).find('.no').text();
    } catch (err) {

    }

    if (pzh == undefined) pzh = "";
    if (pzh == '') {

        //找到左边最近的一张凭证号
        //如果该凭证与自已相临，那么就同号，因为可能是同一个凭证的不同分页
        //否则在那个号上加1做为自已的凭证号
        pzh = incLeftNearestPZH(data.id);
        if (pzh > lastPZH) lastPZH = pzh;


    }

    let $setpzh = function (val) {
        if (val == '') {

            var p = find_pzh(data.id, false);
            if (p) p.remove();
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, false);
            return true;
        } else {
            if (val.length - pzh_prefix.length != pzh_len) {
                toastr.error("凭证号(不含前缀)长度必须是" + pzh_len + "位");
                return false;

            }
            g_lastPZH = val; //记下来
            find_pzh(data.id, true).find('.no').text(val);
            book.sheet1.getBrick("imgPool").setImageSelected(data.id, true);
            return true;
        }
    }

    if (!showDlg) {
        $setpzh(pzh);
        return;
    }

    let dlg = inputBox("标记为凭证", "", pzh, "输入凭证号码",

        function (val) { //确认后的回调

            return $setpzh(val);

        }, false,/*不允许为空*/
        //下面是一些事件的切入
        {
            //输入面板初始化完成后
            onContentReady: function () {

                let input = dlg.$content.find('.name');
                input.on('keyup', function () {
                    if (input.val().indexOf(pzh_prefix) != 0) {
                        input.val(pzh_prefix);
                    }
                });
            }
        }
    );




}


//@comment (group=凭证号,caption=得到图片的凭证号如果有的话,needRightControl=false)
function getPZH(id) {
    let obj = find_pzh(id, false);
    if (obj == null) return;
    let s = obj.text();
    s = s.replace(/\s/g, '');
    return s;
}

//@comment (group=凭证号,caption=设置图片的凭证号,needRightControl=false)
function setPZH(id, pzh, needDeleteButton) {
    if (needDeleteButton == undefined) needDeleteButton = true
    find_pzh(id, true, needDeleteButton).find('.no').text(pzh);
}

//@comment (group=凭证号,caption=查找或创建凭证号标记对象,needRightControl=false)
function find_pzh(id, create_if_not_exists, needDeleteButton) {

    if (needDeleteButton == undefined) needDeleteButton = true;

    var d = $('#' + id);
    if (!d) {
        $.alert(id + "不存在");
        return null;
    }

    var ret = d.find('.pzh');
    if (ret.length == 0) {
        if (create_if_not_exists) //如果需要创建，则创建它
        {
            d.append(`<div class="pzh" >
                        <div class="no"></div>
                        <div class="delete_pzh"  ${needDeleteButton ? "" : " style='display:none' "} ><i class="fa fa-close" onclick="removePZH('${id}');  event.preventDefault(); event.stopPropagation();"> </i></div>
                      </div>`);
        }
        ret = d.find('.pzh');
    }
    return ret;

}

//@comment (group=图片控件,caption=移除图片看的凭证号标记,needRightControl=false)
function removePZH(id) {
    var p = find_pzh(id, false);
    if (p) p.remove();
}

function cb_selectall_onClick() { doSelect(true); }
function cb_selectnull_onClick() { doSelect(false); }

function doSelect(b) {
    var imgPool = book.sheet1.getBrick('imgPool');
    if (b) {
        imgPool.selectAll();
    } else {
        imgPool.unSelectAll();
    }
}


function cb_path_onClick() {
    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    var path = electron.showOpenDialogSync('');
    if (path == '') return;
    if (!path.endsWith('凭证影像采集目录')) {

        $.alert("目录名必须是：“凭证影像采集目录”，盘符及上级目录随意。");
        return;
    }
    var hostName = electron.getHostName();
    setMonitePath(hostName, path);

    moniteStart(path);


}

//@comment (group=上传相关,caption=开始文件变化监控,needRightControl=false)
function moniteStart(path) {
    pathToMonit = path;
    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit);

    if (electron == null) {
        toastr.error("此功能仅能在客户端APP中执行");
        return;
    }

    book.sheet0.cells('stateBar').setValue("图片目录 " + pathToMonit + " 监控中...");
    electron.ipcSendMessage({ cmd: "moniteStart", path: path });
}

function cb_refresh_onClick() {
    newImgCommingTipVisible(false);

    // 先保存当前选中状态及设置的凭证号信息
    saveSelectionAndPZInfo();

    var imgPool = book.sheet1.getBrick('imgPool');
    imgPool.reInit(restoreSelectionAndPZInfo); //重新初始化 ,并在初始化完成后， 恢复选中状态

    toastr.info("重新加载完成");



}

//@comment (group=上传相关,caption=上传好一个文件后，通知有新文件,needRightControl=false)
//@comment (group=上传相关,caption=上传好一个文件后通知有新文件,needRightControl=false)
function newImgCommingTipVisible(v) {
    book.sheet0.getBrick('shineText').visible = v;

}

//@comment (group=上传相关,caption=刷新当前还有多少文件要上传的提示,needRightControl=false)
function notifyNeedUploadFileCount(fc) {
    var info = fc == 0 ? "" : "【" + fc + "】个文件正准备上传";
    book.sheet0.cells("stateInfo2").setValue(info);
}


//@comment (group=归档,caption=凭证归档,needRightControl=false)
function cb_auto_onClick() {

    var imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    var selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }

    let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
    let nn = imgs.length - selection.length;
    if (nn > 0) {
        $confirm("提示", "有" + nn + "张图片没有选中，确信要继续吗?", function () {
            do_pack(selection);
        });
    } else {
        do_pack(selection);
    }
}

var pzGroup = [];

//@comment (group=归档,caption=归档操作,needRightControl=false)
function do_pack(selection) {
    pzGroup = [];
    let pzh2Config = {}; //凭证号对应的配置信息 ， 辅助数据
    let lastPZ = null;
    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        let pzh = getPZH(one.id);
        if (pzh == '') {
            if (lastPZ != null) {
                lastPZ.fj.push(one.id);
            }
        } else {
            //新的凭证号
            if (pzh2Config[pzh] == null) {
                lastPZ = {};
                lastPZ.pzh = pzh;
                lastPZ.fj = []; //附件图片
                lastPZ.pz = []; //凭证图片
                pzh2Config[pzh] = lastPZ; //记下凭证号与配置对象的对应关系
                pzGroup.push(lastPZ); //加入到总配置中
            } else {
                //已经存在配置，说明它是该凭证号的更多的分页图片
                //需要检测，它的左边是不是也是同一个号的凭证
                lastPZ = pzh2Config[pzh];

                let leftID = findLeftImageId(one.id); //找到它左边那张图片的ID
                if (leftID == '') {
                    toastr.error("不可能出现的情况");
                    return;
                }
                let leftPZH = getPZH(leftID);
                if (leftPZH != pzh) {
                    $.alert(pzh + '有多张图片，请将它们移动到相邻位置，即同一张凭证的多个分页必须连续相邻，它们之间不要穿插附件图片或其它凭证号图片');
                    return;
                }

            }
            lastPZ.pz.push(one.id); //凭证图片，同一个凭证可能有多个图片 
        }
    }

    if (pzGroup.length == 0) {
        toastr.error("凭证归档操作，至少需要标记一张凭证，并选中它");
        return;
    }

    console.dir();


    do_pzgdqr();



}

//@comment (group=归档,caption=归档确认,needRightControl=false)
function do_pzgdqr() {

    // 整理归档配置信息用于显示
    book.sheet4.paintPermit = false;

    $gd_ds.reset();
    for (let i = 0; i < pzGroup.length; i++) {
        let one = pzGroup[i];
        let row = $gd_ds.insertRow(9999);
        $gd_ds.setValue(row, { pzh: one.pzh, pzs: one.pz.length, fjs: one.fj.length, hj: one.pz.length + one.fj.length });
    }
    book.sheet4.paintPermit = true;

    book.sheet4.popup('fa fa-cog', '归档确认', 450, 450, true, true, {
        action1: {
            text: '确认',
            btnClass: 'btn-green',
            action: function () {
                do_pzgd();
                return true;    //表示关闭弹窗
            }
        },
        cancel: {
            text: '关闭',
            btnClass: 'btn-red',
            action: function () {

                return true;
            }
        }

    });

}
//@comment (group=归档,caption=归档,needRightControl=false)
function do_pzgd() {
    showInfoPane('*正在归档...');
    setButtonsStatus(false); //禁用一些按钮点击
    //alert(JSON.stringify(pzGroup));
    runTask("归档",
        {
            corpid: book.sheet4.cells("corpid").getValueString(),
            ym: book.sheet4.cells("ym").getValueString(),
            pzGroup: pzGroup
        }, function (ret) {
            hideInfoPane();
            ret = JSON.parse(ret);

            if (ret.success) {

                setButtonsStatus(true); //启用一些按钮点击
                smartRetrieve(book.sheet2, "dzpz_pz"); //刷新凭证列表
                //重新检索图片区
                cb_refresh_onClick();
            } else {
                $.alert(ret.message);
            }

        });
}

function setButtonsStatus(b) {

    book.sheet0.getBrick('cb_auto').enabled = b;
}

//@comment (group=,caption=调取某个凭证,needRightControl=false)
function loadPZ(id, pzh, verified) {
    book.sheet3.cells("id").setValue(id);
    smartRetrieve(book.sheet3, "one");
    //附件图片清单
    //不能从 $one_ds中取数，因为上面的smartRetrieve 是异步的
    let action = (verified == 0) ? "edit" : "view";
    book.sheet3.getBrick('cb_delete_pz').visible = verified == 0;
    var FJ = book.sheet3.getBrick('FJ');
    FJ.config.action = action; //控制是否显示删除和新增按钮
    let data = getPZFJ(id); //得到凭证的所有图片
    FJ.buildGridly(data, function () {
        let shortPZH = pzh.substring(pzh_prefix.length);
        //加载图片完成后， 如果是凭证，那么加上凭证号信息
        for (let i = 0; i < data.length; i++) {
            if (data[i].groupname == '凭证') {
                setPZH(data[i].id, shortPZH, false);
            }
        }

    });
    book.sheet3.yOffset = 0; //垂直卷滚条归位
}


//@comment (group=,caption=删除凭证，并把图片回归到池中,needRightControl=false)
function cb_delete_pz_onClick() {
    $confirm("提示", "确信删除本凭证，并将图片全部回归到待归档状态吗?", function () {
        book.sheet3.getBrick('cb_delete_pz').visible = false;
        var id = $one_ds.getString(0, "id");
        var ret = deletePZAndPutBackToPool(id);
        if (ret.success) {
            $one_ds.reset();
           reload_pzh_info(); //可能删除的就是最后一张凭证，所以要重新取一下
            var FJ = book.sheet3.getBrick('FJ');
            FJ.config.action = 'view';
            FJ.buildGridly([]);
            cb_refresh_onClick();//刷新池中图片

        } else {
            toastr.error(ret.message);
        }
    });

}



function cb_trash_onClick() {
    var url = runTask("urlForTrash", {});
    openInMainFrame(url, false, 'fa-trash', '图片回收站');

}

function cb_deleteSelection_onClick() {
    let imgPool = book.sheet1.getBrick('imgPool');
    // 保存当前选中状态及设置的凭证号信息
    let selection = imgPool.getSelectedImageList();
    if (selection.length == 0) {
        toastr.error("至少选中一张图片");
        return;
    }
    let nn = selection.length;
    $confirm("提示", "确信将选中的" + nn + "张图片移入回收站吗?", function () {
        showInfoPane('*正在移和回收站');
        setTimeout(function () {
            do_trush(selection);
            hideInfoPane();
        }, 100);
    });

}

function do_trush(selection) {

    for (let i = 0; i < selection.length; i++) {
        let one = selection[i];
        moveImageToRecycle(one.id);

    }
    cb_refresh_onClick();

}

function cb_size_onClick() {
    let RPM = book.sheet0.RPM;
    let h = RPM.getRowHeight(1);
    if (h > 1) {
        RPM.setRowStretchHeight(1, 0);//弹性高度取消
        RPM.setRowHeight(1, 1);

        RPM.setRowHeight(2, 0);
        book.sheet0.getBrick('dbnav').visible = false;

    } else {

        RPM.setRowStretchHeight(1, 40);//弹性高度取消
        RPM.setRowHeight(1, 300);

        RPM.setRowHeight(2, 30);
        book.sheet0.getBrick('dbnav').visible = true;
    }
}


/**
 * 单元格的值发生了改变
 * @param sheet  所在的工作表
 * @param cell  单元格对象
 * @param oldValue  原先的值
 * @param newValue 变化后的值
 * @param innerRow   当单元格没有绑定数据库或绑定到单行数据库时，本参数无意义。如果绑定一个
 * 多行数据库，则表示该单元所绑定的字段的第 innerRow行发生变化
 */
function cellValueChanged(sheet, cell, oldValue, newValue, innerRow) {

    //通过别名来判断
    if (sheet.name == '凭证清单') {
        if (cell.alias == 'nian' || cell.alias == 'yue') {
           reload_pzh_info();
        };
    }

}


function reload_pzh_info()
{
    var sheet=book.getWorkSheet ('凭证清单') ;
     //加载帐套信息及年月
            var corpid = sheet.cells("corpid").getValueString();
            
            var nian = sheet.cells("nian").getValueString();
            var yue = sheet.cells("yue").getValueString();
            var ym = nian + right("00" + yue, 2);

            //得到年月后，获取凭证号相关设置
            pzh_len = getPZHLen(corpid);
            pzh_prefix = getPZHPrefix(corpid, ym);
            getLastPZH(corpid, ym, function (v) {
                if (v == '') v = pzh_prefix + '00000000'.substring(8 - pzh_len, 8);
                lastPZH = v;
              
            });

            smartRetrieve(sheet, "dzpz_pz"); //刷新凭证列表
}


