/*-------------------------------文档信息-----------------------------------
///功能：预提单
///创建人: 翟新乐
///创建时间：----------------------
///修改人：------------------------
///修改时间：-----------------------
///修改原因：-----------------------
///详细说明：-----------------------
---------------------------------------------------------------------*/
var strDivP050501 = "divP0505";            //弹出层
var strTableTp050501 = "Tp050501";          //gridId
var strRecordsP050501 = 5;                       //表格数据的行数
var iRowP050501 = 1;                             //行
var iColP050501 = 1;                             //列
var objRecords = [];                              //修改取得的数据
var objGzbh = 0;                         //预提方式0，按数量；1，按金额

//格式金额方法
function formatterP050501b1(cellValue) {
    if (!isNaN(parseFloat(cellValue)) && parseFloat(cellValue)!=0) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式金额方法2
function formatterP050501Money(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式数量方法
function formatterP050501b2(cellValue) {
    if (!isNaN(parseFloat(cellValue)) && parseFloat(cellValue)!=0) {
        return parseFloat(cellValue).toFixed(window.parent.strCountPlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式化百分号方法
function formatPercentPlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue * 100).toFixed(window.parent.strPercentPlace) + "%";
    }
    else {
        return "&nbsp;";
    }
}

//取消格式化百分号方法
function unformatPercentPlace(cellValue, options, rowObject) {
    if (/\d+%$/.test(cellValue)) {
        return cellValue.replace("%", "")/100;
    }
    else {
        return "&nbsp;";
    }
}

//数据状态方法
function dataChangeStateP050501(bState) {
    //修改Data change状态
    $("#" + strDivP050501 + "_divform").data("change", bState);
}

//自定义grid
function createGridP050501(strTableID, objColNames, objColModel) {
    $("#" + strTableID).jqGrid({
        datatype: "local",
        colNames: objColNames,
        colModel: objColModel,
        data: [],
        rownumbers: true,
        rowNum: 9999,
        sortname: "id",
        autowidth: true,
        //height: "100%",
        footerrow: true,
        cellEdit: true,
        cellsubmit: "clientArray",
        gridview: true,
        rownumWidth: 30
    }); //.parent(".ui-jqgrid-bdiv").siblings().css("width", "100%");
    //增加表头‘序号’列
    //$("table.ui-jqgrid-htable th:first", $("#gbox_" + strTableID)).text("序号");
    $("#" + strTableID).setLabel("rn", "序号");
}

//添加空白行
function AddEmptyRowP050501() {
    for (var i = 999999999; i < 999999999 + strRecordsP050501; i++) {
        $("#" + strTableTp050501).addRowData(i, { flag: "" });
    }
    resizeGridScroll(strTableTp050501);
}

//打开窗口方法
function showDialog_P050501(strDjbh) {
    try {
        $(".operate").remove();
        objRecords = null;
        creatDiv_ShowDlgHaveTbl(strDivP050501, "预提单", false, false, strTableTp050501, "800");
        $("#idMust", $("#" + strDivP050501)).append("NO:" + strDjbh);
        creatDialogItem_P050501(strDjbh);
    } catch (e) { }
}

//创建表单元素方法
function creatDialogItem_P050501(strDjbh) {
    var config = ParseData(window.external.DoOptions(strTableTp050501, "GetTableConfig", "{}")); 
    if (config == null) {
        window.parent.cihoAlert(msg.other.modelInfoFail);
        return;
    }

    if (strDjbh != "") {
        objRecords = ParseData(window.external.DoOptions(strTableTp050501, 'GetList', "{\"djbh\":\"" + strDjbh + "\"}"));
    }

    //创建头部
    var i = 0;
    var strForm = "";
    var Item;
    strForm += "<ul>";
    for (i = 0; i < config.pageHeader.length; i++) {
        Item = config.pageHeader[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            if (Item.index == "jsrmc") {
                strForm += "<li class='inp_70'>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "'";
                strForm += " maxlength='50'   onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>";
                strForm += "</li>";
            }
            else {
                strForm += "<li class='inp_100'>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "'disabled ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "'";
                strForm += " maxlength='50'   onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>";
                strForm += "</li>";
            }
        }
        else {
            strForm += "<li>";
            strForm += Item.xsmc + "：";
            strForm += "<select name='" + Item.index + "' id='" + Item.index + "'";
            strForm += " class='easyui-combobox' >";
            strForm += "</select>";
            strForm += "</li>";
        }

    }
    strForm += "</ul>";
    strForm += "<table id=" + strTableTp050501 + "></table>";
    //strForm += "</br></br></br>";
    $("#" + strDivP050501 + "_divform").append(strForm);
    //添加按钮
    strForm = "<div class=\"clr\"></div>";
    strForm += "<div class=\"box_btn_width\">";
    strForm += "    <div class=\"box_btn\">";
    strForm += "        <div class=\"btn01\"><a onclick=\"saveMyData('" + strDivP050501 + "', 1, '" + strTableTp050501 + "')\">保存退出</a></div>";
    strForm += "    </div>";
    strForm += "</div>";
    $(".pop_box", $("#" + strDivP050501)).append(strForm);
    //下拉框
    loadComData_P050501();
    //预提方式：0，按数量；1，按金额
    if (objRecords.Records.length != "0") {
        objGzbh = objRecords.Records[0].ytfs;   //预提方式
        $("#djtypebh", "#" + strDivP050501).combobox("setValue", objRecords.Records[0].yttype); //预提类型
        $("#ywdjbh", "#" + strDivP050501).val(escape(objRecords.Records[0].ywdjbh));            //业务单据编号
        $("#jsrmc", "#" + strDivP050501).combobox("setText", objRecords.Records[0].jsrmc);      //经手人
        $("#jsrmc", "#" + strDivP050501).combobox("setValue", objRecords.Records[0].jsrdm);
        $("#kmmc", "#" + strDivP050501).combobox("setText", objRecords.Records[0].kmmc);        //费用科目
    }    
    //创建表格
    createGridP050501(strTableTp050501, config.colNames, config.colModel);
    //$("#gbox_" + strTableTp050501).css("height", "157");
    $("#" + strTableTp050501).setGridHeight(141);
    resizeGridScroll(strTableTp050501);
    //初始化grid设置
    initGridSetP050501(strTableTp050501, strDivP050501); 

    if (objRecords != undefined) {
        //加载表格数据
        loadTreeData(strTableTp050501, objRecords.Records);
        if (objRecords.Records == "{}") {
            objRecords.Records = "";
        }
        strRecordsP050501 = objRecords.Records.length > 5 ? objRecords.Records.length - objRecords.Records.length : (5 - objRecords.Records.length);
    }
    else {
        strRecordsP050501 = 5;
    }
    //合计
    GetTotalP050501();
    //空白hang
    AddEmptyRowP050501();
    //设定状态
    $(":input", $("#" + strDivP050501 + "_divform")).change(function () {
        dataChangeStateP050501(true);
    });
    $("#" + strDivP050501).dialog("option", "position", "center");
    dataChangeStateP050501(false);
    //释放内存
    config = null;
    strForm = null;
    Item = null;
    i = null;
}

//加载combobox的方法
function loadComData_P050501() {
    var objJsr = ParseData(window.external.DoOptions("Tp0505", "GetComboBoxData", "{'fb':'1'}")).Records;
    var objKjkm = ParseData(window.external.DoOptions("Tp0505", "GetComboBoxData", "{'fb':'2'}")).Records;
    //费用经手人
    $("#jsrmc", "#" + strDivP050501).combobox({
        textField: "jsrmc",
        valueField: "jsrdm",
        width: _iWidth100,
        listWidth: _iWidth100,
        editable: true,
        onChange: function (newValue, oldValue) {
            dataChangeStateP050501(true);
        }
    });
    $("#jsrmc", "#" + strDivP050501).combobox("loadData", objJsr);

    //费用科目
    $("#kmmc", "#" + strDivP050501).combobox({
        textField: "kmmc",
        valueField: "kmdm",
        width: _iWidth100,
        listWidth: _iWidth100,
        onChange: function (newValue, oldValue) {
            dataChangeStateP050501(true);
        }
    });
    $("#kmmc", "#" + strDivP050501).combobox("loadData", objKjkm);

    //业务类型
    $("#djtypebh", "#" + strDivP050501).combobox({
        textField: "mc",
        valueField: "dm",
        width: _iWidth100,
        listWidth: _iWidth100,
        panelHeight: 42
    });
    var strYwlx = [{ "dm": "0", "mc": "销售" }, { "dm": "1", "mc": "回款"}];
    $("#djtypebh", "#" + strDivP050501).combobox("loadData", strYwlx);
    $(".layoutpanel").css("z-index", "50000009");
    //释放内存
    objJsr = {};
    objKjkm = {};
    strYwlx = {};
}

//初始化grid事件
function initGridSetP050501(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterSaveCell": afterSaveCell_P050501,
        "beforeSaveCell": function (rowId, cellname, value, iRow, iCol) {
            if (cellname == "a3") {
                if (objGzbh == "1") {
                    return value / 100;
                }
                else {
                    return value;
                }
            }
        },
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            iRowP050501 = iRow;
            iColP050501 = iCol;
            var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
            switch (cellname) {
                case "a2":      //金额
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                    break;
                case "a1":      //数量
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                    break;
                case "a3":      //预提比例
                    if (objGzbh == "1") {
                        value = (value * 100).toFixed(window.parent.strPercentPlace);
                        if (isNaN(value)) {
                            value = "";
                        }
                    }
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                    break;
                case "a4":      //预提金额
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            }
            item.change(function () { dataChangeStateP050501(true); });
        }
    });
    if (objGzbh == "1") { //预提方式为金额时，格式化为百分号
        $("#" + tbId).setColProp("a3", { formatter: formatPercentPlace, unformat: unformatPercentPlace });
    }
    else {  //预提方式为数量时，格式化为money
        $("#" + tbId).setColProp("a3", { formatter: formatterP050501Money });
    }
    $("#" + tbId).setColProp("a2", { formatter: formatterP050501b1 });
    $("#" + tbId).setColProp("a1", { formatter: formatterP050501b2 });
    $("#" + tbId).setColProp("a4", { formatter: formatterP050501Money });
}

//单元格保存方法
function afterSaveCell_P050501(rowid, cellname, value, iRow, iCol) {
    var objTable = $("#" + strTableTp050501);
    var strSl = 0;      //数量
    var strYtbl = 0;    //预提比列
    var strJe = 0;      //金额
    var strB1 = 0;      //预提金额
    if (cellname == "a3") {
            strSl = objTable.getCell(rowid, "a1");
            strYtbl = objTable.getCell(rowid, "a3");
            strJe = objTable.getCell(rowid, "a2");
            if (objGzbh == "1") {
                if (strJe) {
                    //$("#" + strTableTp050501).setCell(rowid, "a4", (strJe * strYtbl).toFixed(window.parent.strMoneyPlace));
                    $("#" + strTableTp050501).setCell(rowid, "a4", strJe * value);
                }
            }
            else {
                $("#" + strTableTp050501).setCell(rowid, "a4", (strSl * strYtbl).toFixed(window.parent.strMoneyPlace));
            }
    }
    strB1 = objTable.getCell(rowid, "a4");
    if (isNaN(parseFloat(strB1))) {
        objTable.setCell(rowid, "a4","&nbsp;");
    }
    else {
        strB1 = parseFloat(strB1);
        objTable.setCell(rowid, "a4", parseFloat(strB1).toFixed(window.parent.strMoneyPlace));
    }
    GetTotalP050501();
    //释放内存
    objTable = null;
    strSl = null;
    strYtbl = null;
    strJe = null;
    strB1 = null;
}

//合计方法
function GetTotalP050501() {
    var objTable = $("#" + strTableTp050501);
    var arrIds = objTable.getDataIDs();
    var strSl = 0;      //数量
    var strJe = 0;      //金额
    var strYtje = 0;    //预提金额
    for (var i = 0; i < arrIds.length; i++) {
        var intNumSl = parseFloat(objTable.getCell(arrIds[i], "a1"));
        if (!isNaN(intNumSl)) {
            strSl += intNumSl;
        }
        var intNumJe = parseFloat(objTable.getCell(arrIds[i], "a2"));
        if (!isNaN(intNumJe)) {
            strJe += intNumJe;
        }
        var intNumYtje = parseFloat(objTable.getCell(arrIds[i], "a4"));
        if (!isNaN(intNumYtje)) {
            strYtje += intNumYtje;
        }
    }
    objTable.footerData("set", { rn: "合计",
        a1: parseFloat(strSl).toFixed(window.parent.strCountPlace),
        a2: parseFloat(strJe).toFixed(window.parent.strMoneyPlace),
        a4: parseFloat(strYtje).toFixed(window.parent.strMoneyPlace)
    });
    //释放内存
    objTable = null;
    arrIds = null;
    strSl = null;
    strJe = null;
    strYtje = null;
}

//保存方法
function saveMyData_P050501(save) {
    //头部
    var strData = "{";
    strData += "\"djbh\":\"" + objSelRowP0505.djbh + "\"";      //单据编号
    //费用经手人
    var strLxValue = $("#jsrmc", $("#" + strDivP050501 + "_divform")).combobox('getValue');
    if (!strLxValue) {
        if (objRecords.Records.length!="0" && objRecords.Records != "{}" && $("#jsrmc", "#" + strDivP050501).combobox('getText') == objRecords.Records[0].jsrmc) {
            strLxValue = objRecords.Records[0].jsrdm;
        }
        else {
            window.parent.cihoAlert(msg.cw.fyjsrNotEmp, null, function () { $("#jsrmc", $("#" + strDivP050501 + "_divform")).combobox('focus'); });
            return false;
        }
    }
    strData += ",\"jsrdm\":\"" + strLxValue + "\"";
    //表格的数据
    strData += ",Records:[";
    var objTable = $("#" + strTableTp050501);
    objTable.saveCell(iRowP050501, iColP050501);
    var arrIds = objTable.getDataIDs();
    var bAddTable = false;
    var strHjje = 0;
    //var intYtHj = 0;
    for (var i = 0; i < arrIds.length; i++) {
        var objTr = objTable.getRowData(arrIds[i]);
        if (objTr.khmc == "") {
            continue;
        }
        var strIndex = objTable.getInd(arrIds[i]);
        var alterMsg = "";
        var strytbl;
        strData += "{";
        strData += "\"mxguid\":\"" + objTr.mxguid + "\",";
        if (objTr.a3==""||objTr.a3==undefined||objTr.a3=="&nbsp;") {
            alterMsg += msg.other.dnh + strIndex + msg.cw.ytblNotEmp;
            window.parent.cihoAlert(alterMsg);
            return;
        }
//        if (objGzbh == "1") {
//            strytbl = objTr.a3/100 ;
//        }
//        else {
//            strytbl = objTr.a3;
//        }
        if (objTr.a4 == "" || objTr.a4 == undefined) {
            alterMsg += msg.other.dnh + strIndex + msg.cw.ytjeNotEmp;
            window.parent.cihoAlert(alterMsg);
            return;
        }
        strHjje += parseFloat(objTr.a4);
        bAddTable = true;
        strData += "\"a3\":\"" + objTr.a3 + "\",";
        strData += "\"a4\":\"" + objTr.a4 + "\"";
        strData += "},";
    }
    if (bAddTable == false) {
        window.parent.cihoAlert(msg.kc.notDataEmp);
        return false;
    }
    if (strData.substring(strData.length - 1, strData.length) != "[") {
        strData = strData.substr(0, strData.length - 1);
    }
    strData += "]";
    if (strHjje > window.parent._MaxPerBill) {  //合计预提金额大于1亿
        window.parent.cihoAlert(msg.other.djhjExtent);
        return;
    }
    strData += ",\"a1\":\"" + strHjje + "\"}";
    var objResult = ParseData(window.external.DoOptions(strTableTp050501, "Edit", strData));
    if (!objResult) {
        window.parent.cihoAlert(msg.other.dbOprateErr);
        return;
    }
    if (objResult.ReturnCode != "0") {
        window.parent.cihoAlert(objResult.MSG);
        return;
    }
    //清除修改数据
    loadGridDataP0505();
    //resizeGrid(strTableP0505);
    //释放内存
    iRowP050501 = 1;
    iColP050501 = 1;
    objTable = null;
    strRecordsP050501 = 5;
    objRecords = {};
    objGzbh = 0;
    strData = null;
    strytbl = null;
    strHjje = null;
    objTr = null;
    strIndex = null;
    strLxValue = null;
    cihoDlgClose(strDivP050501);
}