/*-------------------------------文档信息-----------------------------------
///功能：应收调整单
///创建人: 翟新乐
///创建时间：------------------------
///修改人：------------------------
///修改时间：-----------------------
///修改原因：-----------------------
///详细说明：-----------------------
---------------------------------------------------------------------*/
var strTableP020201 = "Tp020201";           //tableName 全局变量
var strDlgIdP020201 = "divP0202";           //弹出层id  全局变量
var bSvaeSignP020201 = "1";                   //标志位
var objconfig;              //列配置
var objRetRecord=[];       //修改时保存要修改的记录
var iRowP020201 = 1;    //当前选中单元格的row索引
var iColP020201 = 1;    //当前选中单元格的col索引
var iRowIdP020201 = 1;  //当前选中单元格的rowid

//在jqGrid中自定义下拉框
//创建select表单元素的方法
function my_inputP020201(value, options) {
    return $('<select name="' + options.name + '" id="' + options.id + ' name="' + options.id + '""></select>').addClass("easyui-combobox");
}

//保存选中的值的方法
function my_valueP020201(ele) {
    return ele.combobox('getText');
}

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

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

//释放内存
function freeMemory_P020201() {
    bSvaeSignP020201 = "1";
    objconfig;
    objRetRecord = [];
    iRowP020201 = 1;
    iColP020201 = 1;
    iRowIdP020201 = 1;
}

//打开窗口的方法
function showDialog_P020201(strType) {
    try {
        $(".operate").remove();
        //清空弹出窗口内容
        $("#" + strDlgIdP020201).empty();

        //把弹出窗口框架及底部按钮添加到父窗口创建dialog中
        creatDiv_ShowDlgHaveTbl(strDlgIdP020201, "应收调整单", false, true, strTableP020201, "650");
        objconfig = ParseData(window.external.DoOptions(strTableP020201, 'GetTableConfig', '{}')); //获得jqGrid的列名和属性
        if (!objconfig) {
            window.parent.cihoAlert(msg.other.modelInfoFail);
            return;
        }
        //添加表单元素到窗口中
        tableFormP020201(strType);

        if ("1" == strType) {   //添加
            //值为1，插入数据；值为2，更新数据
            bSvaeSignP020201 = "1"; 
            //加载空记录
            $("#" + strTableP020201).addRowData(1, {});
        }
        else if ("2" == strType) {         //修改
            bSvaeSignP020201 = "2";
            //设定单据的原始值
            setDjValueP020201();
            iRowIdP020201 = $("#" + strTableP020201).jqGrid("getDataIDs")[0];
            //修改时，时间不可再编辑
            for (var intI = 0; intI < objconfig.colModel.length; intI++) {
                if (objconfig.colModel[intI].index == "djdate") {
                    $("#" + strTableP020201).setColProp("djdate", { editable: false });
                }
            }
        }
        //$("#" + strDlgIdP020201).dialog("option", "position", "center");
        //设定data change 为false
        dataChangeState(false);

        setTimeout('$("#a4", "#" + strDlgIdP020201).focus();', 100);
    } catch (e) { }
}

//添加表单元素的方法
function tableFormP020201(strType) {
    var strpageFooter = objconfig.pageFooter;   //页尾字段
    var strTable = "<table id=" + strTableP020201 + "></table>";
    $("#"+strDlgIdP020201+"_divform").append(strTable);
    //页脚
    var strDown = "<ul>";
    for (var i = 0; i < strpageFooter.length; i++) {
        if (strpageFooter[i]["name"]=="a4") {
            strDown += "<li class=\"bz\">";
            strDown += strpageFooter[i]["xsmc"] + ": <input id='" + strpageFooter[i]["index"] + "' name='" + strpageFooter[i]["name"] + "' type='text'";
            strDown += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>"; //限制输入，粘贴特殊字符
            strDown += "</li>";
        }
        else {
            strDown += "<li class=\"inp_70\">";
            strDown += strpageFooter[i]["xsmc"] + ": <input id='" + strpageFooter[i]["index"] + "' name='" + strpageFooter[i]["name"] + "' type='text'";
            strDown += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>"; //限制输入，粘贴特殊字符
            strDown += "</li>";
        }            
    }
    strDown += "</ul>";
    $("#" + strDlgIdP020201 + "_divform").append(strDown);
    //创建表格
    createGridP020201(strTableP020201, objconfig.colNames, objconfig.colModel);
    //$("#gbox_" + strTableP020201).css("height", "53");
    $("#" + strTableP020201).setGridHeight(47);
    resizeGridScroll(strTableP020201);
    //设置属性custom:绑定combobox：关联药品
    $("#" + strTableP020201).setColProp("spmc", { edittype: "custom" });
    $("#" + strTableP020201).setColProp("spmc", { editoptions: { custom_element: my_inputP020201, custom_value: my_valueP020201} });
    //调整类型
    $("#" + strTableP020201).setColProp("tzlx", { edittype: "custom" });
    $("#" + strTableP020201).setColProp("tzlx", { editoptions: { custom_element: my_inputP020201, custom_value: my_valueP020201} });
    //客户
    $("#" + strTableP020201).setColProp("khmc", { edittype: "custom" });
    $("#" + strTableP020201).setColProp("khmc", { editoptions: { custom_element: my_inputP020201, custom_value: my_valueP020201} });
    //销售员
    $("#" + strTableP020201).setColProp("zymc", { edittype: "custom" });
    $("#" + strTableP020201).setColProp("zymc", { editoptions: { custom_element: my_inputP020201, custom_value: my_valueP020201} });
    //编辑状态，绑定事件

    $("#" + strTableP020201).setGridParam({ afterEditCell: afterEditCellP020201 });
    //设定制单人
    $("#czymc", $("#" + strDlgIdP020201 + "_divform")).attr("disabled", true);
    $("#czymc", $("#" + strDlgIdP020201 + "_divform")).val(window.parent.objLoginInfo.name);

    //设定状态
    $(":input[name]", $("#" + strDlgIdP020201 + "_divform")).change(function () {
        dataChangeState(true);
    });
    //释放内存
    strTable = null;
    strDown = null;
    strpageFooter = null;
}

//修改时，设定单据的原值的方法
function setDjValueP020201() {
    objRetRecord = ParseData(window.external.DoOptions(strTableP020201, 'GetList', "{'djbh':'" + objSelRowP0202.djbh + "'}"));
    if (!objRetRecord) {
        window.parent.cihoAlert(msg.other.dbOprateErr);
        return;
    }
    else {
        if (objRetRecord.Records == "{}") {
            window.parent.cihoAlert(msg.other.dataEmp);
            return;
        }
        else {
            //填充表格 格式数据
            $("#" + strTableP020201).setColProp("a3", { formatter: formatMoneyPlace });
            $("#" + strTableP020201).setColProp("a2", { formatter: formatCountPlace });
            loadTreeData(strTableP020201, objRetRecord.Records);
        }
    }
    //加载调整单编号
    $("#idMust", $("#" + strDlgIdP020201)).append("NO:" + objSelRowP0202.djbh);
    //制单人
    $("#czymc", $("#" + strDlgIdP020201 + "_divform")).val(objRetRecord.Records[0]["czymc"]);
    //备注
    $("#a4", $("#" + strDlgIdP020201 + "_divform")).val(escape(objRetRecord.Records[0]["a4"]));
}

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

//编辑状态，设置单元格属性的方法
function afterEditCellP020201(rowId, cellname, value, iRow, iCol) {
    iRowIdP020201 = rowId;
    iRowP020201 = iRow;
    iColP020201 = iCol;
    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
    switch (cellname) {
        case "spmc":            //药品
            item.combobox({
                width: _iWidth80,
                listWidth: _iWidth80,
                valueField: "dm",
                textField: "mc",
                editable: true
            });

            var objSpxx = getComboboxData('Tspxx');
            objSpxx.push({ "mc": "<font color='red'>添加药品</font>", "dm": "-1" });
            //加载数据
            item.combobox("loadData", objSpxx);
            //设定选中值
            item.combobox("setValue", $(this).getCell(rowId, "spdm"));
            if (item.combobox("getText") == $(this).getCell(rowId, "spdm")) {
                item.combobox('setText',value);
            }
            item.combobox('focus');
            //关联药品
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (!newValue) {
                        $("#" + strTableP020201).setCell(rowId, "spdm", "&nbsp;");
                    }
                    else {
                        $("#" + strTableP020201).setCell(rowId, "spdm", newValue);
                    }
                    //修改Data change状态
                    dataChangeState(true);
                },
                afterChange: function (newValue, newText) {
                    if (newValue == "-1") {     //添加药品
                        ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                        ciho.showTypeDialog();
                        $(this).combobox("setValue", "");
                    }
                }
            });
            break;
        case "khmc":            //客户单元格设置
            var objKhxx = getComboboxData('Tkhxx1');        //客户信息
            objKhxx.push({ "mc": "<font color='red'>添加客户</font>", "dm": "-1" });
            item.combobox({
                width: _iWidth80,
                listWidth: _iWidth80,
                valueField: "dm",
                textField: "mc",
                editable: true
            });
            //加载数据
            item.combobox("loadData", objKhxx== "{}" ? [] : objKhxx);

            //设定选中值
            item.combobox("setValue", $(this).getCell(rowId, "khdm"));
            item.combobox("setText", value);
            if (item.combobox("getText") == $(this).getCell(rowId, "khdm")) {
                item.combobox('setText', value);
            }
            item.combobox('focus');
            //关联客户
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (!newValue) {
                        $("#" + strTableP020201).setCell(rowId, "khdm", "&nbsp;");
                    }
                    else {
                        $("#" + strTableP020201).setCell(rowId, "khdm", newValue);                        
                    }
                    //修改Data change状态
                    dataChangeState(true);
                },
                afterChange: function (newValue, newText) {
                     $(this).combobox("setText", newText.replace(/&nbsp;/g, ""));       //替换空格
                    if (newValue == "-1") {     //添加客户
                        ciho.IniData({ id: "divAddType", title: "客户", table: "Tflxx" }, { model: "Tkhxx", jquery: $(this) });
                        ciho.showTypeDialog();
                        $(this).combobox("setValue", "");
                    }
                }

            });
            break;
        case "zymc":            //销售员单元格设置
            item.combobox({
                width: _iWidth80,
                listWidth: _iWidth80,
                valueField: "dm",
                textField: "mc",
                editable: true
            });
            //加载数据
            var objZyxx = getComboboxData('TZyxx');         //销售员信息
            objZyxx.push({ "mc": "<font color='red'>添加销售员</font>", "dm": "-1" });
            item.combobox("loadData", objZyxx == "{}" ? [] : objZyxx);

            //设定选中值
            item.combobox("setValue", $(this).getCell(rowId, "zydm"));
            if (item.combobox("getText") == $(this).getCell(rowId, "zydm")) {
                item.combobox('setText', value);
            }
            item.combobox('focus');
            //关联职员
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (!newValue) {
                        $("#" + strTableP020201).setCell(rowId, "zydm", "&nbsp;");
                    }
                    else {
                        $("#" + strTableP020201).setCell(rowId, "zydm", newValue);
                    }
                    //修改Data change状态
                    dataChangeState(true);
                },
                afterChange: function (newValue, newText) {
                    if (newValue == "-1") {     //添加销售员
                        ciho.IniData({ id: "divAddType", title: "销售员", table: "Tflxx" }, { model: "TZyxx", jquery: $(this) });
                        ciho.showTypeDialog();
                        $(this).combobox("setValue", "");
                    }
                }
            });
            break;
        case "tzlx":
            //调整类型
            item.combobox({
                width: _iWidth80,
                listWidth: _iWidth80,
                valueField: "dm",
                textField: "mc",
                editable: false,
                panelHeight: 42,
                onChange: function (newValue, oldValue) {
                    //修改Data change状态
                    dataChangeState(true);
                },
                onSelect: function (Record) {
                    if (Record.dm != null && Record.dm != undefined) {
                        //djtypebh:该列隐藏，保存使用，此处用来保存combobox调整类型的key值。
                        $("#" + strTableP020201).setCell(rowId, "djtypebh", Record.dm);
                    }
                    else {
                        $("#" + strTableP020201).setCell(rowId, "djtypebh", "");
                    }
                }
            });

            //加载数据
            var arrTzlx = [{ "dm": "301", "mc": "应收款增加" }, { "dm": "302", "mc": "应收款减少"}];
            item.combobox("loadData", arrTzlx);
            //设定选中值
            item.combobox("setValue", $(this).getCell(rowId, "djtypebh"));
            item.combobox('focus');

            break;
        case "djdate":
            inputAndBindData(":input[name='djdate']", false, "#" + strDlgIdP020201, dateChange_P020201);
            //change无效
            $(":input[name='djdate']","#" + strDlgIdP020201).change(function () { dataChangeState(true) });
            break;
        case "a3":          //调整金额
            item.val(value);
            item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled").attr("maxlength", "7");
            item.change(function () { dataChangeState(true) });
            break;
        case "a2":          //数量
            item.val(value);
            item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            item.change(function () { dataChangeState(true) });
            break;
    }
    
    $(".layoutpanel").css("z-index", "50000009");
}

//日期控件变更dataChange
function dateChange_P020201() {
    dataChangeState(true);
}

//保存数据的方法
function saveDataP020201(strType) {
    //数据有效性验证,组织要保存的数据
    var strRecord = checkDataValidateP020201();
    if (!strRecord) {
        return;
    }

    //添加
    if (bSvaeSignP020201 == "1") {
        var objRet = ParseData(window.external.DoOptions(strTableP020201, 'Add', strRecord));
    }
    else { //修改
        var objRet = ParseData(window.external.DoOptions(strTableP020201, 'Edit', strRecord));
    }
    if (!objRet) {
        window.parent.cihoAlert(msg.other.dbOprateErr);
        return;
    }

    //操作成功
    if ("0" == objRet.ReturnCode) {
        //重新加载管理画面数据
        loadGridDataP0202();
        //resizeGrid(strTableP0202);
        //释放内存
        strRecord = null;
        objRet = null;

        $("#idMust", $("#" + strDlgIdP020201)).empty();
        //保存新增
        if (strType == "2") {
            bSvaeSignP020201 = "1";
            //清空当前窗口数据
            $(":input[name]", $("#" + strDlgIdP020201 + "_divform")).val("");
            //清除单据编号
            $("#" + strDlgIdP020201 + "_pop_box_top").empty();

            $("#czymc", $("#" + strDlgIdP020201 + "_divform")).val(window.parent.objLoginInfo.name); //制单人

            //清空表格中的元素
            $("#" + strTableP020201).jqGrid("clearGridData");
            //加载空记录
            $("#" + strTableP020201).addRowData(1, {});
            for (var intI = 0; intI < objconfig.colModel.length; intI++) {
                if (objconfig.colModel[intI].index == "djdate") {
                    $("#" + strTableP020201).setColProp("djdate", { editable: true });
                }
            }
            //表单元素置为未修改
            dataChangeState(false);
            setTimeout(function () { $("#a4", "#" + strDlgIdP020201).focus(); }, 100);
        }
        //保存退出/关闭
        else {
            //关闭当前窗口
            cihoDlgClose(strDlgIdP020201);
        }
        freeMemory_P020201();
    }
    //操作失败，弹出提示消息
    else {
        window.parent.cihoAlert(objRet.MSG);
    }
}

//验证并组成json串的方法
function checkDataValidateP020201() {
    //取消表格中的数据的编辑状态，保存数据
    $("#" + strTableP020201).saveCell(iRowP020201, iColP020201);
    var arrList = "";
    if (bSvaeSignP020201 == "1") {
        //制单人
        arrList += "\"czydm\":\"" + window.parent.objLoginInfo.code + "\",";
    }
    else {
        //制单人
        arrList += "\"czydm\":\"" + objRetRecord.Records[0]["czydm"] + "\",";
    }

    //备注
    arrList += "\"a4\":\"" + trim($("#a4").val()) + "\"";
    //获得表格的数据
    var strSpdm = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "spdm");    //药品
    if (!strSpdm) {
        window.parent.cihoAlert(msg.sz.yp.empOrNotExit);
        return;
    }
    var strKhdm = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "khdm");    //客户
    if (!strKhdm) {
        window.parent.cihoAlert(msg.sz.kh.empOrNotExit);
        return;
    }
    var strZydm = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "zydm");    //销售员
    var strSl = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "a2");        //数量
    var strDjdate = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "djdate");    //时间
    if (!strDjdate) {
        window.parent.cihoAlert(msg.dt.dtExtentErr);
        return;
    }
    else {
        if (checkDatePattern(strDjdate) == false) {
            window.parent.cihoAlert(msg.dt.dtTypeErr);
            return;
        }
       else if ((strDjdate.replace(/-/g, "/")) < (window.parent._startDate.replace(/-/g, "/"))) {
            window.parent.cihoAlert(msg.other.djrqExtent, null, function () { $("#djdate").focus(); });
            return;
        }
        strDjdate = formatDate(strDjdate);
    }
    var strJe = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "a3");    //金额
    if (!strJe) {
        window.parent.cihoAlert(msg.other.jenotEmp);
        return;
    }
//    else {
//        if (parseFloat(strJe)<=0) {
//            window.parent.cihoAlert(msg.other.tzjeNotZero);
//            return;
//        }
//    }
    var strTzlx = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "tzlx");    //调整类型
    if (!strTzlx) {
        window.parent.cihoAlert(msg.other.typeErr);
        return;
    } else {
        if (strTzlx == "应收款减少") {
            strTzlx = "1";
        }
        else {
            strTzlx = "0";
        }
    }
    
    var strDjtypebh = $("#" + strTableP020201).jqGrid("getCell", iRowIdP020201, "djtypebh");    //调整类型的key值
    var strRecord = "{";
    strRecord += "\"mxguid\":\"\",";
    strRecord += "\"djbh\":\"" + objSelRowP0202.djbh + "\",";
    strRecord += "\"spdm\":\"" + strSpdm + "\"";
    strRecord += ",\"khdm\":\"" + strKhdm + "\"";
    strRecord += ",\"zydm\":\"" + strZydm + "\"";
    strRecord += ",\"a1\":\"" + strTzlx + "\"";
    strRecord += ",\"a2\":\"" + strSl + "\"";
    strRecord += ",\"a3\":\"" + strJe + "\"";

    strRecord += ",\"djdate\":\"" + strDjdate + "\"";
    strRecord += ",\"djtypebh\":\"" + strDjtypebh + "\",";
    strRecord += arrList;
    strRecord += "}";
    //释放内存
    strSpdm = null;
    strKhdm = null;
    strZydm = null;
    strTzlx = null;
    strSl = null;
    strJe = null;
    strDjdate = null;
    strDjtypebh = null;
    arrList = null;

    return strRecord;
}

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