# app_script_history

id: 6188e5109932f1a68ca6b8d1
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 17:11:31.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人




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



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

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

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


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

            console.dir(result);

            cb_package_onClick();

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

            hideInfoPane();
        }

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

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

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

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

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


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


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

    });
}




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

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

}



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


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

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

        $dzpz_dy_ds.setValue(0, "ziptaskid", '');
        $dzpz_dy_ds.setValue(0, "zipresult", '');
        form.save(false);
        $q_result_ds.reset();

    });


}

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

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

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

    });
}

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

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

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

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

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


    }

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



function cb_package_onClick___() {

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

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

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

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

    });

}

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


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

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

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

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

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

}

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

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

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

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

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

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

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

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        setTimeout(functoin()
        { 
        do_paste_pzlist(innerRow, newValue) //写入凭证号
        },100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】' + formatDate($dzpz_dy_ds.getValue(0, "billdate"), 'yyyy.mm.dd') + '-凭证调阅'
        })
    }



}

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

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

    }

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

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {
    showInfoPane('*正在分析凭证号');
    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







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

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

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

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

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : $dzpz_dy_ds.getString(0, "watermark")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

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

    });


}

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

    }

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

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

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

        do_removeDuplicated()

    });

}


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

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



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



}


id: 6188e5109932f1a68ca6b8d7
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 17:11:40.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人




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



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

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

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


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

            console.dir(result);

            cb_package_onClick();

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

            hideInfoPane();
        }

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

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

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

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

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


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


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

    });
}




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

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

}



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


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

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

        $dzpz_dy_ds.setValue(0, "ziptaskid", '');
        $dzpz_dy_ds.setValue(0, "zipresult", '');
        form.save(false);
        $q_result_ds.reset();

    });


}

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

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

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

    });
}

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

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

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

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

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


    }

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



function cb_package_onClick___() {

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

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

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

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

    });

}

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


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

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

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

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

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

}

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

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

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

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

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

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

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

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        setTimeout(function()
        { 
        do_paste_pzlist(innerRow, newValue) //写入凭证号
        },100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】' + formatDate($dzpz_dy_ds.getValue(0, "billdate"), 'yyyy.mm.dd') + '-凭证调阅'
        })
    }



}

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

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

    }

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

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {
    showInfoPane('*正在分析凭证号');
    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







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

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

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

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

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : $dzpz_dy_ds.getString(0, "watermark")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

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

    });


}

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

    }

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

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

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

        do_removeDuplicated()

    });

}


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

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



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



}


id: 6188e5109932f1a68ca6b8dd
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 17:11:43.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人




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



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

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

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


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

            console.dir(result);

            cb_package_onClick();

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

            hideInfoPane();
        }

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

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

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

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

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


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


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

    });
}




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

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

}



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


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

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

        $dzpz_dy_ds.setValue(0, "ziptaskid", '');
        $dzpz_dy_ds.setValue(0, "zipresult", '');
        form.save(false);
        $q_result_ds.reset();

    });


}

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

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

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

    });
}

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

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

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

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

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


    }

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



function cb_package_onClick___() {

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

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

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

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

    });

}

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


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

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

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

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

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

}

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

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

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

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

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

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

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

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】' + formatDate($dzpz_dy_ds.getValue(0, "billdate"), 'yyyy.mm.dd') + '-凭证调阅'
        })
    }



}

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

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

    }

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

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {
    showInfoPane('*正在分析凭证号');
    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







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

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

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

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

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : $dzpz_dy_ds.getString(0, "watermark")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

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

    });


}

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

    }

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

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

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

        do_removeDuplicated()

    });

}


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

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



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



}


id: 6188e5109932f1a68ca6b8e3
scriptid: 60fa600f9932563b7c99bb03
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 17:13:19.000
script:
var g_currentUserIsOwner = false; //当前人是不是起草人




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



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

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

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


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

            console.dir(result);

            cb_package_onClick();

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

            hideInfoPane();
        }

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

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

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

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

}

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

}



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

}

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


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

    var RC = excelSheet.length;

    book.sheet0.paintPermit = false;

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


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


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

    });
}




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

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

}



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


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

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

        $dzpz_dy_ds.setValue(0, "ziptaskid", '');
        $dzpz_dy_ds.setValue(0, "zipresult", '');
        form.save(false);
        $q_result_ds.reset();

    });


}

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

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

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

    });
}

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

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

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

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

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


    }

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



function cb_package_onClick___() {

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

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

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

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

    });

}

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


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

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

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

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

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

}

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

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

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

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

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

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

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

    let bind = cell.bind;
    if (bind != null && bind.dataSource == 'dzpz_dymx' && bind.DBCol == 'pzh') {
        showInfoPane('*正在分析凭证号');
        setTimeout(function () {
            do_paste_pzlist(innerRow, newValue) //写入凭证号
        }, 100);
    }
    if (bind != null && bind.dataSource == 'dzpz_dy' && bind.DBCol == 'reader') {
        $dzpz_dy_ds.setValue(0, {
            watermark: '【' + $dzpz_dy_ds.getString(0, "reader") + '】' + formatDate($dzpz_dy_ds.getValue(0, "billdate"), 'yyyy.mm.dd') + '-凭证调阅'
        })
    }



}

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

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

    }

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

}


/**
 * 按钮点击事件
 * 当某个按钮被点击时， 首先触发  {按钮名称}_onClick 事件，然后触发 buttonOnClick事件
 * @param sheet  工作表
 * @param cell   按钮所在的单元格
 * @param button 按钮对象
 */
//@comment (group=do,caption=凭证列表粘贴凭证清单后自动后插并赋值,needRightControl=false)
function do_paste_pzlist(innerRow, newValue) {
    
    if (newValue == null || newValue == '') return;
    let data = newValue.split(' ');
    book.getWorkSheet("detail").paintPermit = false;
    let row = innerRow;
    for (let i = 0; i < data.length; i++) {
        //row = $dzpz_dymx_ds.insertRow(row + 1);
        if (data[i] != '') {
            $dzpz_dymx_ds.setValue(row, {
                pzh: data[i],
                selected: 1
            });
            if (i < data.length - 1) row = $dzpz_dymx_ds.insertRow(row + 1);
        }
    }
    book.getDataSource("dzpz_dymx").currentBindRow = row;
    book.getWorkSheet("detail").View.insureSelectionOnScreen(null, false);
    do_removeDuplicated(); //删除重复项
    book.getWorkSheet("detail").paintPermit = true;
    book.getWorkSheet("main").paintPermit = true;
    hideInfoPane();
}







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

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

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

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

    $confirm('', '确信要重新打包吗?', function () {
        showInfoPane("*正在后台打包...");
        let fileName = $dzpz_dy_ds.getString(0, "reader") +
            formatDate(newDate(), "yyyy.MM.dd HH:mm") + "调阅凭证.zip";
        runTask("后台打包", {
            gguid: currentGUID(),
            fileName: fileName,
            ids: ids,
            watermark: $dzpz_dy_ds.getInt(0, "needwatermark") == 0 ? "" : $dzpz_dy_ds.getString(0, "watermark")
        },
            function (ret) {
                ret = JSON.parse(ret);
                hideInfoPane();
                if (ret.success) {
                    $dzpz_dy_ds.setValue(0, "ziptaskid", ret.zipTaskId);
                    form.save(false);
                    hideInfoPane();

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

    });


}

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

    }

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

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

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

        do_removeDuplicated()

    });

}


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

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



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



}


id: 6188ead59932f1a68ca6b990
scriptid: 609d3cfc5db2b0a331d6bb4b
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 17:27:10.000
script:
function getImageList1()
{
    return getImageList("");
}
function getImageList2()
{
    return getImageList("回收站");
}


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

    return  { success:true,  data:ret};

}

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

}

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

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

}


id: 618922649932f1a68ca6b9fa
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 23:27:32.000
script:
function main(arg)
{

    var targetSize =1024;
    
    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/default/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak/";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            if( j>3) return; 


        }
    }

    println( 'over');

}


id: 618922649932f1a68ca6ba03
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 23:28:16.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/default/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak/";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            if( j>3) return; 


        }
    }

    println( 'over');

}


id: 618922649932f1a68ca6ba0b
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.08 23:28:24.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/default/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak/";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            if( j>3) return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba13
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:35:12.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak/";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            if( j>3) return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba1c
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:39:38.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            if( j>3) return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba24
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:40:07.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    var root="/mnt/dzpz_appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba2c
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:42:20.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            imageResize( sourceFile , targetSize) ;
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba34
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:46:12.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bkFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba3c
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:46:39.000
script:
function main(arg)
{

    var targetSize =1024;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba44
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:49:49.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba4c
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:52:58.000
script:
function main(arg)
{

    var targetSize =1446;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"'  and objectname like '%6173a0309932ec8e75d082b5%'");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 618951c09932f1a68ca6ba54
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 00:54:27.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"'  and objectname like '%6173a0309932ec8e75d082b5%'");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
            
            return; 


        }
    }

    println( 'over');
    return 'over';

}


id: 61895b6c9932fda9010e6a68
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 01:19:58.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"'  and objectname like '%6173a0309932ec8e75d082b5%'");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
            println( err);
        

        }
    }

    println( 'over');
    return 'over';

}


id: 61895b6c9932fda9010e6a70
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 01:20:07.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"'  and objectname like '%6173a0309932ec8e75d082b5%'");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
           

        }
    }

    println( 'over');
    return 'over';

}


id: 61895b6c9932fda9010e6a85
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 01:21:20.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
           

        }
    }

    println( 'over');
    return 'over';

}


id: 61895ce79932fda9010e6a8e
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 01:22:47.000
script:
function main(arg)
{

    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            println( (i+1)+"/"+ m ); 
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
           

        }
    }

    println( 'over');
    return 'over';

}


id: 61895ce79932fda9010e6a98
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:05:36.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-check",   // 字符图标
                    "选中此前",  // 鼠标悬停的提示信息
                    "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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6a9e
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:07: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();
    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-plus",   // 字符图标
                    "选中此前",  // 鼠标悬停的提示信息
                    "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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6aa4
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:13:03.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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {
                let img = $('#' + id).find('.image');

                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, true);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6aaa
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:13: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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "gray", //按钮背景色
            function (id) {
                let img = $('#' + id).find('.image');

                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, true);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6ab0
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:14:53.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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "lightgreen", //按钮背景色
            function (id) {
                let img = $('#' + id).find('.image');

                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, true);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6abc
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:37: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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {
                let  selected= $('#' + id).parent().find('.brickSelected').length>0;
                
                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, !selected);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6ac2
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:38:40.000
script:
var pathToMonit = "";//当前监控的目录
var electron = null;
var pzh_prefix = ""; // 凭证号前缀
var pzh_len = 0; //凭证号长度
var lastPZH = "";
var fullScreenDiv = null;

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

function formOpen() {

    book.sheet4.visible = false;

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

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

    //加载帐套信息及年月
    var 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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {
                let  selected= $('#' + id).parent().find('.brickSelected').length>0; // 可以用 imgPool.isImageSelected( id) 替换，但此时本函数还没有提供
                
                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, !selected);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 61895ce79932fda9010e6ac8
scriptid: 60a321f05db27838e0c014c3
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 07:38:49.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-plus",   // 字符图标
            "选中此前",  // 鼠标悬停的提示信息
            "green", //按钮背景色
            function (id) {
                let  selected= $('#' + id).parent().find('.brickSelected').length>0; // 可以用 imgPool.isImageSelected( id) 替换，但此时本函数还没有提供，以后可以换成此函数
                
                let imgPool = book.sheet1.getBrick("imgPool");
                let imgs = imgPool.getCurrentSortedImageList();//得到当前排序后的图片清单
                let found = false;
                for (let i = 0; i < imgs.length; i++) {
                    imgPool.setImageSelected(imgs[i].id, !selected);
                    if (imgs[i].id == id) return;

                }


            });


    }
}


/**
 * 图片控件中图片上的删除按钮被点击
 * @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"); //刷新凭证列表
}


id: 618a0b7a9932fda9010e6f7d
scriptid: 6188ead59932f1a68ca6b9a3
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.09 13:57:14.000
script:
function main(arg)
{

/*

这个函数可以反复执行， 规则是， 如果发现没有bak目录，那么，就创建bak目录，并把图片复制进去， 然后再把图片调整尺寸， 
如果尺寸设置不合适，需要重新改一个尺寸，那么直接改一下 targetSize 再执行一次就好。 再次执行时，发现 bak目录已存在，
那么会重新把图片从bak目录中复制出来， 接新的尺寸重新resize 。 bak中的图片保持不变
*/
    var targetSize =1920;

    var ym='201901';
    //注意， 不是宿主机的目录，是docker容器中的目录
    var root="/usr/local/appFileRoot/FileServer/电子凭证/";

    //找出这个月，上传的图片在哪些目录中
    var ds1= newDataStore("","select    distinct    left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/')) as path  from dzpz_pzfj where gguid in ( select gguid from  dzpz_pz where ym="+ym+ " )   ");
    var n=ds1.retrieve();

    var ds2= newDataStore("", " select objectname from dzpz_pzfj where gguid in (select id from dzpz_pz where ym="+ym+" ) ");

    println( ym+"的文件分布在"+n+"个目录中");
    for( var i=0;i<n;i++)
    {
        var objectPath= ds1.getString(i,'path');
        
        var m= ds2.retrieve("  left ( objectname ,  LENGTH(objectname) - INSTR(REVERSE( objectname),'/'))  = '"+objectPath+"' ");
        println( (i+1)+": "+objectPath +" 中，"+ym+"月的有"+m+"张图片");

        var bakPath= root+ objectPath+"/bak";
        mkDirs( bakPath);
        println("创建备份目录："+ bakPath);
        for( j =0;j<m;j++)
        {
            println( (i+1)+"/"+ m ); 
            var objectName=  ''+ ds2.getString(j,"objectname");
            var sourceFile = root+objectName;
            var onlyName= objectName.substr( objectName.lastIndexOf("/")+1);
            var bakFileName= bakPath + '/'+ onlyName; 
            if( ! fileExists( bakFileName ) )
            {
                println("备份文件："+ onlyName+" 到 "+ bakFileName);
                fileCopy( sourceFile, bakFileName , false); 
            }else{
                println("备份文件"+ bakFileName+" 已存在，把备份文件复制回来，重新resize");
                fileCopy( bakFileName, sourceFile , true) ;
            }

            var err=imageResize( sourceFile , targetSize) ;
           

        }
    }

    println( 'over');
    return 'over';

}


id: 618b5aec9932fda9010e7081
scriptid: 618b531c9932fda9010e7047
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.10 13:39:22.000
script:
create index di_dzpz_pzfj_gguid_groupname_info1 
on dzpz_pzfj ( gguid, groupname, info1) 


create index di_dzpz_pz_corpid_ym_pzh 
on dzpz_pz  ( corpid, ym,pzh  )


id: 618b5e7a5db2b147d47c5b46
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 192.168.1.77
username: sa
createdate: 2021.11.10 14:17:54.000
script:
//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ(id) {
    var ds = newDataStore("", "select id , filename as title, 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") &&  currentUserId()!=1) {

                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: 618b64115db2b147d47c5b4e
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 192.168.1.77
username: sa
createdate: 2021.11.10 14:18:47.000
script:
//@comment (group=,caption=构建凭证附件清单,needRightControl=false)
function getPZFJ(id) {
    var ds = newDataStore("", "select id , filename , 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") &&  currentUserId()!=1) {

                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: 618b64115db2b147d47c5b58
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 192.168.1.77
username: sa
createdate: 2021.11.10 14:18:53.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") &&  currentUserId()!=1) {

                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: 61922d309932fda9010e73f3
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:49:49.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") && currentUserId() != 1) {

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

}



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


id: 61922d309932fda9010e73fb
scriptid: 60c4bd735db2478f9c5a1118
tablename: app_script
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:50:30.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") && currentUserId() != 1) {

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

}



//@comment (group=,caption=图片旋转,needRightControl=false)
function do_imageRotate(id, rt) {
    var ret = imageRotate("", "dzpz_pzfj", id, rt);
    println(JSON.stringify(ret));
    return ret;
}


id: 61922d309932fda9010e7401
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:50:36.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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

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

 

    }
}


id: 61922d309932fda9010e7407
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:51:45.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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

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

 

    }
}


id: 61922d309932fda9010e740d
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:55:51.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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


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

 

    }
}


function rotate( id, degree)
{
    
                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, degree);
                    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);
            
}


id: 61922d309932fda9010e7413
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:55:57.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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


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

 

    }
}


function rotate( id, degree)
{
    
                showInfoPane('*正在旋转图片...');
                setTimeout(function () {
                    //toastr.info(id);  // id 是当前操作的图片对应数据的ID
                    var ret = do_imageRotate(id, degree);
                    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);
            
}


id: 61922d309932fda9010e7419
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:57:19.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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

            }
        );


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

            }
        );



    }
}


function rotateImg(id, degree) {
    let brick = sheet.getBrick('FJ');
    showInfoPane('*正在旋转图片...');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID
        var ret = do_imageRotate(id, degree);
        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);

}


id: 61922d309932fda9010e741f
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 17:58:28.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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

            }
        );


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

            }
        );



    }
}


function rotateImg(sheet, id, degree) {
    let brick = sheet.getBrick('FJ');
    showInfoPane('*正在旋转图片...');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID
        var ret = do_imageRotate(id, degree);
        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);

}


id: 61922d309932fda9010e7429
scriptid: 60c4bd735db2478f9c5a111c
tablename: app_template
clientip: 10.255.0.2
username: sa
createdate: 2021.11.15 18:55:12.000
script:
var pzh_prefix;
var pzh_length;

var fullScreenDiv = null;



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

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

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


    });

    // 追加一些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);
                }
            });

    });
}



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


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

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

            }
        );


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

            }
        );



    }
}


function rotateImg(sheet, id, degree) {
    let brick = sheet.getBrick('FJ');
    alert(1);
    showInfoPane('*正在旋转图片...');
    setTimeout(function () {
        //toastr.info(id);  // id 是当前操作的图片对应数据的ID
        var ret = do_imageRotate(id, degree);
        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);

}


