/*-------------------------------文档信息-----------------------------------
///功能：提成单
///创建人: 翟新乐
///创建时间：----------------------
///修改人：------------------------
///修改时间：-----------------------
///修改原因：-----------------------
///详细说明：-----------------------
---------------------------------------------------------------------*/
var strDivP051001 = "divP051001";            //弹出层
var strTableTp051001 = "Tp051001";          //gridId
var strRecordsP051001 = 5;                       //数据的行数
var iRowP051001 = 1;                             //行号
var iColP051001 = 1;                             //列
var objRecords = [];                              //修改时取得的数据
var objGzbh = 0;                         //提成单的提成方式

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

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

//格式数量方法
function formatterP051001b2(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 dataChangeStateP051001(bState) {
    //修改Data change状态
    $("#" + strDivP051001 + "_divform").data("change", bState);
}

//自定义grid方法
function createGridP051001(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 AddEmptyRowP051001() {
    for (var i = 999999999; i < 999999999 + strRecordsP051001; i++) {
        $("#" + strTableTp051001).addRowData(i, { flag: "" });
    }
    resizeGridScroll(strTableTp051001);
}

//打开窗口的方法
function showDialog_P051001(strDjbh) {
    try {
        $(".operate").remove();
        objRecords = null;
        creatDiv_ShowDlgHaveTbl(strDivP051001, "提成单", false, false, strTableTp051001, "800");
        $("#idMust", $("#" + strDivP051001)).append("NO:" + strDjbh);
        creatDialogItem_P051001(strDjbh);
    } catch (e) { }
}

//创建表单元素的方法
function creatDialogItem_P051001(strDjbh) {
    var config = ParseData(window.external.DoOptions(strTableTp051001, "GetTableConfig", "{}"));    //取得列配置信息
    if (config == null) {
        window.parent.cihoAlert(msg.other.modelInfoFail);
        return;
    }

    if (strDjbh != "") {    //取得数据
        objRecords = ParseData(window.external.DoOptions(strTableTp051001, '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") {
                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=" + strTableTp051001 + "></table>";
    //strForm += "</br></br></br>";
    $("#" + strDivP051001 + "_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('" + strDivP051001 + "', 1, '" + strTableTp051001 + "')\">保存退出</a></div>";
    strForm += "    </div>";
    strForm += "</div>";
    $(".pop_box", $("#" + strDivP051001)).append(strForm);
    //下拉框的值
    $("#ywlx", "#" + strDivP051001).combobox({
        textField: "mc",
        valueField: "dm",
        width: _iWidth80,
        listWidth: _iWidth80,
        panelHeight: 42
    });
    var strYwlx = [{ "dm": "0", "mc": "终端销售" }, { "dm": "1", "mc": "回款"}];
    $("#ywlx", "#" + strDivP051001).combobox("loadData", strYwlx);
    $(".layoutpanel").css("z-index", "50000009");
    //预提方式：0，按数量；1，按金额
    if (objRecords.Records.length != "0") {
        objGzbh = objRecords.Records[0].ytfs;   //预提方式
        $("#ywlx", "#" + strDivP051001).combobox("setValue", objRecords.Records[0].ywlx);   //业务类型
        $("#ywdjbh", "#" + strDivP051001).val(escape(objRecords.Records[0].ywdjbh));        //业务单据编号
        $("#jsrmc", "#" + strDivP051001).val(escape(objRecords.Records[0].jsrmc));          //经手人
        $("#kmmc", "#" + strDivP051001).val("工资提成");                                    //预提科目
    }
    //创建表格
    createGridP051001(strTableTp051001, config.colNames, config.colModel);
    //$("#gbox_" + strTableTp051001).css("height", "157");
    $("#" + strTableTp051001).setGridHeight(141);
    resizeGridScroll(strTableTp051001);
    //初始化grid设置
    initGridSetP051001(strTableTp051001, strDivP051001);
    if (objRecords != undefined) {
        //加载表格数据
        loadTreeData(strTableTp051001, objRecords.Records);

        if (objRecords.Records == "{}") {
            objRecords.Records = "";
        }
        strRecordsP051001 = objRecords.Records.length > 5 ? objRecords.Records.length - objRecords.Records.length : (5 - objRecords.Records.length);
    }
    else {
        strRecordsP051001 = 5;
    }
    //合计
    GetTotalP051001();
    //空白行
    AddEmptyRowP051001();
    //设定状态
    $(":input", $("#" + strDivP051001 + "_divform")).change(function () {
        dataChangeStateP051001(true);
    });
    $("#" + strDivP051001).dialog("option", "position", "center");
    dataChangeStateP051001(false);
    //释放内存
    strYwlx = null;
    config = null;
    Item = null;
    i = null;
    strForm = null;
}

//初始化grid事件方法
function initGridSetP051001(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterSaveCell": afterSaveCell_P051001,
        "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) {
            iRowP051001 = iRow;
            iColP051001 = 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") {
                        //if (value != "&nbsp;") {
                        value = (value * 100).toFixed(window.parent.strPercentPlace);
                        //                        }
                        //                        else {
                        //                            value = "";
                        //                        }
                        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 () { dataChangeStateP051001(true); });
        }
    });
    if (objGzbh == "1") {   //预提方式为金额时，格式化为百分号
        $("#" + tbId).setColProp("a3", { formatter: formatPercentPlace, unformat: unformatPercentPlace });
    }
    else {       //预提方式为数量时，格式化为money
        $("#" + tbId).setColProp("a3", { formatter: formatterP051001Money });
    }
    $("#" + tbId).setColProp("a2", { formatter: formatterP051001b1 });
    $("#" + tbId).setColProp("a1", { formatter: formatterP051001b2 });
    $("#" + tbId).setColProp("a4", { formatter: formatterP051001Money });
}

//单元格保存方法
function afterSaveCell_P051001(rowid, cellname, value, iRow, iCol) {
    var objTable = $("#" + strTableTp051001);
    if (cellname == "a3") {
        var strSl = objTable.getCell(rowid, "a1");      //数量
        var strYtbl = objTable.getCell(rowid, "a3");    //预提比列
        var strJe = objTable.getCell(rowid, "a2");      //金额
        if (objGzbh == "1") {
            //$("#" + strTableTp051001).setCell(rowid, "a4", (strJe * strYtbl / 100).toFixed(window.parent.strMoneyPlace));
            //$("#" + strTableTp051001).setCell(rowid, "a4", (strJe * strYtbl).toFixed(window.parent.strMoneyPlace));
            if (strJe) {
                $("#" + strTableTp051001).setCell(rowid, "a4", strJe * value);
            }
        }
        else {
            $("#" + strTableTp051001).setCell(rowid, "a4", (strSl * strYtbl).toFixed(window.parent.strMoneyPlace));
        }
    }
    var 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));
    }
    GetTotalP051001();
    //释放内存
    objTable = null;
    strB1 = null;
    strSl = null;
    strYtbl = null;
    strJe = null;
}

//计算合计方法
function GetTotalP051001() {
    var objTable = $("#" + strTableTp051001);
    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_P051001(save) {
    //头部
    var strData = "{";
    strData += "\"djbh\":\"" + objSelRowP0510.djbh + "\"";  
    //表格的数据
    strData += ",Records:[";
    var objTable = $("#" + strTableTp051001);
    objTable.saveCell(iRowP051001, iColP051001);
    var arrIds = objTable.getDataIDs();
    var bAddTable = false;
    var strHjje =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 = 0;
        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 += ",\"je\":\"" + strHjje + "\"}";
    var objResult = ParseData(window.external.DoOptions(strTableTp051001, "Edit", strData));
    if (!objResult) {
        window.parent.cihoAlert(msg.other.dbOprateErr);
        return;
    }
    if (objResult.ReturnCode != "0") {
        window.parent.cihoAlert(objResult.MSG);
        return;
    }
    //清除修改数据
    loadGridDataP0510();
    //resizeGrid(strTableP0510);
    //释放内存
    iRowP051001 = 1;
    iColP051001 = 1;
    objTable = null;
    strRecordsP051001 = 5;
    objRecords = {};
    objGzbh = 0;
    strHjje = null;
    strytbl = null;
    alterMsg = null;
    objTr = null;
    strIndex = null;
    strData = null;
    cihoDlgClose(strDivP051001);
}