/*************************
*功能：会计凭证录入
*创建人：张振华
*时间：2010-08-15
*备注：此时间是加注释时间
*************************/

var strDivP050401 = "divP050401";
var strTableP050401 = "Tp050401";
var strOptrTypeP050401; //保存标志位
var objRecordsP050401;  //修改时保存单据
var strRecordsCountP050401; //表格中的记录条数
var strDeletHtmlP050401 = "";   //删除的数据
var iRowP050401;    //行索引
var iColP050401;    //列索引
var iFristIndexP050401 = 999999999;

//创建grid
function createGridP050401(strTableID, objColNames, objColModel) {

    $("#" + strTableID).jqGrid({
        datatype: "local",
        sortname: "id",
        colNames: objColNames,
        colModel: objColModel,
        data: [],
        rowNum: 9999999,
        footerrow: true,
        rownumbers: true,
        autowidth: true,
        rownumWidth: 30,
        cellEdit: true,
        cellsubmit: "clientArray",
        gridview: true
    }).parent(".ui-jqgrid-bdiv").siblings();

    //增加表头‘序号’列
    $("table.ui-jqgrid-htable th:first", $("#gbox_" + strTableID)).text("序号");
}

//自定义元素
function my_inputP050401(value, options) {
    var strHtml = "<input id=\"" + options.id + "\" class=\"ciho-Input\"  name=\"" + options.name + "\" >";
    return $(strHtml);
}

//获取自定义元素的值
function my_valueP050401(ele) {

    return ele.cihoComboTree('getText');
}

//格式化金额
function formatterP050401Money(cellValue) {

    if (!isNaN(parseFloat(cellValue)) && parseFloat(cellValue) != 0) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}

//修改Data change状态
function dataChangeStateP050401(bState) {
    $("#" + strDivP050401 + "_divform").data("change", bState);
}

//该变保存状态
function changeFlagP050401(rowId) {

    var objTable = $("#" + strTableP050401);
    if (objTable.getCell(rowId, "mxguid") == "") {
        objTable.setCell(rowId, "flag", "1");

    }
    else {
        objTable.setCell(rowId, "flag", "2");
    }

    objTable = null;
}

//编辑之后事件
function afterEditCell_P050401(rowId, cellname, value, iRow, iCol) {

    //行索引，类索引
    iRowP050401 = iRow;
    iColP050401 = iCol;

    //table对象，单元格中的控件
    var objTable = $("#" + strTableP050401);
    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);

    //根据列配置加载不同的信息
    switch (cellname) {
        case "kmmc":
            //取树形控件的数据 (会计科目)
            var objResult = ParseData(window.external.DoOptions(strTableP050401, "GetComboBoxData", '{}'));
            var strKmdm = objTable.getCell(rowId, "kmdm");

            //加载数据
            item.cihoComboTree({
                width: 120,
                showBox: false
            });
            item.cihoComboTree('loadData', objResult.Records);

            //设定当前值，加事件
            if (item.cihoComboTree("getText") != "" && item.cihoComboTree("getText") == strKmdm) {
                var strMcSp = "";
                for (var j = 0; j < objRecordsP050401.length; j++) {
                    if (objRecords[j].id == rowid) {
                        strMcSp = objRecordsP050401[j].kmmc;
                        break;
                    }
                }

                item.cihoComboTree('setText', strMcSp);
            }
            item.cihoComboTree({
                onSelect: function (Record) {
                    if (Record.dm != undefined) {
                        objTable.setCell(rowId, "kmdm", Record.dm);
                    }
                    else {
                        objTable.setCell(rowId, "kmdm", "&nbsp;");
                    }
                    dataChangeStateP050401(true);
                    changeFlagP050401(rowId);
                }
            });
            item.cihoComboTree('setValue', strKmdm);
            item.cihoComboTree('setText', value);
            item.cihoComboTree("focus");

            break;
        case "jfje":
            //借方
            var strDfje = objTable.getCell(rowId, "dfje");
            if (strDfje != "" && strDfje != false) {
                objTable.restoreCell(iRow, iCol);
            }
            //退货数量
            item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        case "dfje":
            //贷方
            var strJfje = objTable.getCell(rowId, "jfje");
            if (strJfje != "" && strJfje != false) {
                objTable.restoreCell(iRow, iCol);
            }
            item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
    }

    //单元格控件加事件
    item.change(function () { dataChangeStateP050401(true); changeFlagP050401(rowId); });

    //释放内存
    item = null;
}

//保存之后的事件
function afterSaveCell_P050401(rowId, cellname, value, iRow, iCol) {
    switch (cellname) {
        case "dfje":
        case "jfje":
            getTotalP050401();
            break;
        default:
    }
}

//计算合计
function getTotalP050401() {

    //table对象，行ID
    var objTable = $("#" + strTableP050401);
    var arrIds = objTable.getDataIDs();

    //借方金额，贷方金额
    var strTotalDfje = 0;
    var strTotalJfje = 0;

    //循环计算合计
    for (var i = 0; i < arrIds.length; i++) {
        var strDfje = parseFloat(objTable.getCell(arrIds[i], "dfje"));
        var strJfje = parseFloat(objTable.getCell(arrIds[i], "jfje"));
        if (!isNaN(strDfje)) {
            strTotalDfje += strDfje;
        }
        if (!isNaN(strJfje)) {
            strTotalJfje += strJfje;
        }
    }

    //表格底部设置值
    $("#" + strTableP050401).footerData("set", { rn: "合计", dfje: strTotalDfje, jfje: strTotalJfje }, true);

    //释放内存
    objTable = null;
}

//释放内存
function freeMemory_P050401() {
    strOptrTypeP050401 = null;
    iRowP050401 = null;
    iColP050401 = null;
    objCompDataP020102 = null;
    objRecordsP050401 = null;
    strDeletHtmlP050401 = "";
}

//弹出层
function showDialogP050401(strType) {
    try {

        //清楚浮动层
        $(".operate").hide();

        strOptrTypeP050401 = strType;

        //弹出空层
        creatDiv_ShowDlgHaveTbl(strDivP050401, "录入凭证", false, true, strTableP050401, "600");

        //往层理添加内容
        if (strOptrTypeP050401 == "1") {
            addContentP050401("");
        }
        else if (strOptrTypeP050401 == "2") {
            $("#idMust").append("NO:" + objSelRowP0504.djbh);
            addContentP050401(objSelRowP0504.djbh);
        }
        $("#bz", "#" + strDivP050401).focus();                  //给摘要设置焦点
    }
    catch (e) {
        proceError("P050401", e.ToString());
    }

}

//页面加载时添加空行
function addEmptyRowsP050401() {
    for (var i = iFristIndexP050401; i < iFristIndexP050401 + strRecordsCountP050401; i++) {
        $("#" + strTableP050401).addRowData(i, { flag: "" });
    }
}

//添加一空行
function addEmptyRowP050401() {
    $("#" + strTableP050401).addRowData(++strRecordsCountP050401 + iFristIndexP050401, {});
    addCzHtmlP050401();

    //调整表格宽度
    resizeGridScroll(strTableP050401);
}

//添加浮动删除
function addCzHtmlP050401() {
    $("#" + strTableP050401).delegate("tr[id]:visible", "hover", function (e) {
        if (e.type == "mouseenter") {
            var strButtonHtml = "";
            strButtonHtml += "<a  style=\"color:red;text-decoration:none;cursor:pointer;\" onclick=\"deleteDataP050401(" + this.id + ");return false;\">删除</a> ";
            $("#" + strTableP050401).jqGrid("setCell", this.id, "cz", strButtonHtml);
        }
        else if (e.type == "mouseleave") {
            $("#" + strTableP050401).jqGrid("setCell", this.id, "cz", "&nbsp;");
        }
    });
}

//添加弹出层内容
function addContentP050401(strDjbh) {

    //配置信息和数据
    var config = ParseData(window.external.DoOptions(strTableP050401, "GetTableConfig", "{}"));

    //常用变量
    var i = 0;
    var strForm = "";
    var Item;

    //修改的时候获取数据，否则是空
    objRecordsP050401 = { Records: [] };
    if (strDjbh != "") {
        objRecordsP050401 = ParseData(window.external.DoOptions(strTableP050401, 'GetList', '{djbh:' + strDjbh + ' }'));
    }


    //配置显示头部
    strForm = "<ul>";
    for (i = 0; i < config.pageHeader.length; i++) {

        Item = config.pageHeader[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            strForm += "<li class='inp_70'>";
            strForm += Item.xsmc + "：";
            strForm += "<input type='text' class=\"easyui-combotree\"   name='" + Item.index + "' ";
            strForm += " value=''  ";
            strForm += " id='" + Item.index + "'>";
            strForm += "</li>";
        }
    }
    strForm += "</ul>";
    strForm += "<table id=" + strTableP050401 + "></table>";

    //配置显示尾部
    strForm += "<ul>";
    for (i = 0; i < config.pageFooter.length; i++) {

        Item = config.pageFooter[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            if (Item.index == "bz") {
                strForm += "<li class='bz'>";
                strForm += Item.xsmc + "：";
                strForm += "<input  type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "' onkeypress='return checkValidate(event)' onpaste='return validatePaste()' >";
                strForm += "</li>";
            } else {
                strForm += "<li class='inp_150'>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "' onkeypress='return checkValidate(event)' onpaste='return validatePaste()' >";
                strForm += "</li>";
            }
        }
    }
    strForm += "</ul>";

    //添加到弹出层里
    $("#" + strDivP050401 + "_divform").append(strForm);

    //动态创建的表格对象
    var objTable = $("#" + strTableP050401);

    //创建表格重设高度
    createGridP050401(strTableP050401, config.colNames, config.colModel);
    $("#" + strTableP050401).setGridHeight(141);


    //表格头部增加添加按钮
    $(".ui-jqgrid-htable th:visible:last").html('<img id="btnAddP050401"  style="cursor:pointer"  title="添加行" src="../../Content/Default/images/edit_add.gif" onclick="addEmptyRowP050401(); "/>');

    //设置属性
    objTable.setColProp("jfje", { formatter: formatterP050401Money });
    objTable.setColProp("dfje", { formatter: formatterP050401Money });
    objTable.setColProp("kmmc ", { edittype: "custom" });
    objTable.setColProp("kmmc", { editoptions: { custom_element: my_inputP050401, custom_value: my_valueP050401} });

    //表格添加事件
    objTable.setGridParam({ afterEditCell: afterEditCell_P050401 });
    objTable.setGridParam({ afterSaveCell: afterSaveCell_P050401 });

    //加载数据
    loadTreeData(strTableP050401, objRecordsP050401.Records);

    //计算添加空行，不足五行补齐五行
    if (objRecordsP050401.Records == "{}") {
        objRecordsP050401.Records = [];
    }
    strRecordsCountP050401 = objRecordsP050401.Records.length > 5 ? objRecordsP050401.Records.length : (5 - objRecordsP050401.Records.length);

    if (strRecordsCountP050401 <= 5) {
        addEmptyRowsP050401();
    }

    //计算合计
    getTotalP050401();

    //添加浮动删除
    addCzHtmlP050401();

    //单据日期绑定事件，设置默认值
    $("#djdate", "#" + strDivP050401).val(getNowDate());
    inputAndBindData("djdate");
    $("#djdate", "#" + strDivP050401).blur(function () {
        $("#" + strDivP050401 + "_divform").data("change", true);
    });

    //设置当前制单人
    $("#czymc", "#" + strDivP050401).attr("disabled", true);
    $("#czymc", "#" + strDivP050401).val(window.parent.objLoginInfo.name);

    //备注加事件
    $("#bz", "#" + strDivP050401).focus(function () { this.select(); });

    //修改时加载数据
    if (strOptrTypeP050401 == "2") {
        $("#djdate", "#" + strDivP050401).val(objRecordsP050401.djdate);
        $("#bz", "#" + strDivP050401).val(escape(objRecordsP050401.bz));
        $("#djdate", "#" + strDivP050401).attr("disabled", true);
        $("#czymc", "#" + strDivP050401).val(objRecordsP050401.czymc);
    }

    //设定状态
    $(":input", $("#" + strDivP050401 + "_divform")).change(function () {
        $("#" + strDivP050401 + "_divform").data("change", true);
    });
    $("#" + strDivP050401 + "_divform").data("change", false);

    //调整表格
    resizeGridScroll(strTableP050401);

    //释放内存
    objTable = null;
    config = null;

}

//检查表单
function checkForm(strDialog, strType) {

    //检查单据日期
    if ($("#djdate", "#" + strDivP050401).val() == "") {
        window.parent.cihoAlert(msg.other.PzNoEmpty, null, function () { $("#djdate", "#" + strDivP050401).focus(); });
        return false;
    }

    //验证日期
    if (checkDatePattern($("#djdate", "#" + strDivP050401).val()) == false) {
        window.parent.cihoAlert(msg.dt.dtTypeErr, msgBox.dlgBtn.Ok, function () { });
        return false;
    }

    //验证早于起始时间
    if ($("#djdate", "#" + strDivP050401).val().replace(/-/g, "/") < window.parent._startDate) {
        window.parent.cihoAlert(msg.other.pzrqExtent, null, function () { $("#djdate", "#" + strDivP050401).focus(); });
        return false;
    }

    //表格中是否一条数据都没有是false
    var bAddContent = false;

    //表格对象，行ID，消息字符串
    var objTable = $("#" + strTableP050401);
    var arrIds = objTable.getDataIDs();
    var alterMsg;

    //保存编辑的单元格
    objTable.saveCell(iRowP050401, iColP050401);

    //循环表格里面
    for (var i = 0; i < arrIds.length; i++) {

        //取行对象
        var objTr = objTable.getRowData(arrIds[i]);

        //如果行未编辑不进入循环
        if (objTr.flag == "") {
            continue;
        }

        //如果这行中一条数据没有也不验证
        if (checkEmptyRow(objTr, "flag,mxguid,glsl,a6,djbh")) {
            continue;
        }

        //表示有数据
        bAddContent = true;

        //会计科目不能为空
        if (objTr.kmdm == "") {
            alterMsg = msg.other.dnh + (i + 1) + "】" + msg.sz.kjkm.nameEmp;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

        //借方和贷方不能都为空
        if (objTr.jfje == "" && objTr.dfje == "") {
            alterMsg = msg.other.DfJfNoEmpty;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

    }

    //表格中是否有记录
    if (bAddContent == false) {
        window.parent.cihoAlert(msg.other.djNotExit);
        return false;
    }

    //表格底部的数据
    var objFootData = objTable.footerData('get');

    //借贷平衡
    if (parseFloat(objFootData.jfje) != parseFloat(objFootData.dfje)) {
        alterMsg = msg.other.DfNoSameJf;
        window.parent.cihoAlert(alterMsg);
        return false;
    }

    //金额不能过大
    if (parseFloat(objFootData.jfje) > window.parent._MaxPerBill || parseFloat(objFootData.dfje) > window.parent._MaxPerBill) {
        window.parent.cihoAlert(msg.other.djhjExtent);
        return false;
    }

    //释放内存
    objTable = null;

}

//保存到数据库
function saveToDbP050401(strDialog, strType) {

    //表格对象，行ID
    var objTable = $("#" + strTableP050401);
    var arrIds = objTable.getDataIDs();

    //保存数据库后返回的结果,传给数据库的字符串
    var objResult;
    var strData = "{";

    //拼接字符串
    if (strOptrTypeP050401 == "2") {
        strData += "\"djbh\":\"" + objSelRowP0504.djbh + "\",";
    }
    strData += "\"djdate\":\"" + $("#djdate", "#" + strDivP050401).val() + "\"";
    strData += ",\"czydm\":\"" + window.parent.objLoginInfo.code + "\"";
    strData += ",\"bz\":\"" + trim($("#bz", "#" + strDivP050401).val()) + "\"";
    strData += ",Records:["

    //拼接表格里的字符串
    for (var i = 0; i < arrIds.length; i++) {

        //行对象
        var objTr = objTable.getRowData(arrIds[i]);
        if (objTr.flag == "") {
            continue;
        }
        if (i != 0) {
            strData += ",";
        }
        strData += "{";

        strData += "\"kmdm\":\"" + objTr.kmdm + "\"";
        strData += ",\"jfje\":\"" + objTr.jfje + "\"";
        strData += ",\"dfje\":\"" + objTr.dfje + "\"";
        strData += ",\"flag\":\"" + objTr.flag + "\"";
        if (strOptrTypeP050401 == "2") {
            strData += ",\"mxguid\":\"" + objTr.mxguid + "\"";
        }
        strData += "}"
    }

    //把删除的数据组进来
    if (strDeletHtmlP050401 != "") {
        strData += strDeletHtmlP050401;
    }

    strData += "]";
    strData += "}";

    //数据库操作
    if (strOptrTypeP050401 == "1") {
        //新增
        objResult = ParseData(window.external.DoOptions(strTableP050401, "Add", strData));
    }
    else if (strOptrTypeP050401 == "2") {
        //修改
        objResult = ParseData(window.external.DoOptions(strTableP050401, "Edit", strData));
    }

    //数据库操作失败弹出提示
    if (objResult.ReturnCode != "0") {
        window.parent.cihoAlert(objResult.MSG);
        return;
    }

    //爆粗按钮
    if (strType == "2") {

        //保存新增
        $("#" + strTableP050401).clearGridData();
        strRecordsCountP050401 = 5;
        addEmptyRowsP050401();
        getTotalP050401();
        addCzHtmlP050401();

        $(":input", $("#" + strDivP050401)).val("");

        $("#czymc", "#" + strDivP050401).val(window.parent.objLoginInfo.name);
        $("#djdate", "#" + strDivP050401).val(getNowDate());
        $("#djdate", "#" + strDivP050401).attr("disabled", false);
        $("#bz", "#" + strDivP050401).focus();                      //设置摘要的焦点
        $("#idMust", "#" + strDivP050401).empty();
    }
    else {

        //保存退出
        strRecordsCountP050401 = null;
        cihoDlgClose(strDialog);
    }

    //设定状态
    $("#" + strDivP050401 + "_divform").data("change", false);

    //释放内存
    objTable = null;
    strOptrTypeP050401 = "1";
    strDeletHtmlP050401 = "";
    iRowP050401 = -1;
    iColP050401 = -1;
    objRecordsP050401 = null;

    //重新加载管理画面数据
    searchDataClickP504();

}

//保存数据
function saveMyDataTp050401(strDialog, strType) {

    //验证
    if (checkForm(strDialog, strType) == false) {
        return;
    }

    //验证通过保存
    saveToDbP050401(strDialog, strType);
}

//删除
function deleteDataP050401(rowId) {
    try {
        //删除的那行的数据
        var objTr = $("#" + strTableP050401).getRowData(rowId);

        //保存时取消单元格编辑
        $("#" + strTableP050401).saveCell(iRowP050401, iColP050401);

        //判断改行是否有数据
        if (checkEmptyRow(objTr, "glsl,cz") == false) {

            //判断关联数量
            if (objTr.glsl && objTr.glsl != "0") {
                window.parent.cihoAlert(msg.del.delForbid);
                return;
            }

            //删除时提示
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    if (strOptrTypeP050401 == "2" && objTr.mxguid != "") {

                        //修改的时候
                        strDeletHtmlP050401 += ",{\"mxguid\":\"" + objTr.mxguid + "\",";
                        strDeletHtmlP050401 += "\"flag\":\"3\"}";

                        $("#" + strTableP050401).delRowData(rowId);
                    }
                    else {
                        //新增的时候
                        $("#" + strTableP050401).delRowData(rowId);

                    }
                    dataChangeStateP050401(true);
                    //重新计算合计
                    getTotalP050401();

                    //调整表格宽度
                    resizeGridScroll(strTableP050401);
                    return;
                }
            });
        }
        else {
            $("#" + strTableP050401).delRowData(rowId);
            //调整表格宽度
            resizeGridScroll(strTableP050401);
        }

    }
    catch (e) {
        proceError("P050401", e.ToString());
    }
}