var searchParam = {};
var cellX, cellY, records = [], alterdata = {}, alterState;
var bLoadComplete = false;
var fpbh = "";

//初始化管理页面
function pageLoad_P0401() {
    try {
        initInputsP0401();

        //向后台请求配置信息
        var config = ParseData(window.external.DoOptions(strTableP0401, "GetTableConfig", "{}"));
        //创建管理界面的grid
        createGrid(strTableP0401, config.colNames, config.colModel, [], null, null, true, ondblclickRow);

        //绑定grid事件
        bindGridEventP0401();

        //格式化grid
        $("#" + strTableP0401).setColProp("a1", { formatter: formatMoneyPlace });       //发票金额
        $("#" + strTableP0401).setColProp("zt", { formatter: function (cellvalue) {
            if (cellvalue == 0) { return "未抵扣"; }
            if (cellvalue == 1) { return "已抵扣"; }
            if (cellvalue == 2) { return "已退票"; }
        }
        });

        //创建管理界面底部的分页
        createPage(strPageP0401, strTableP0401);
        resizeGrid(strTableP0401, true, true);

        //查询数据
        searchDataClick_P0401(1);


        config = null;
    } catch (e) { }
}

//初始化input控件
function initInputsP0401() {
    $("#sjtype,#gysdmP0401,#fptypebh,#fpbh").combobox();
    addArrowClass();

    //为起始时间和结束时间绑定日期控件
    inputAndBindData("sdate", false, "", dateChange);
    inputAndBindData("edate", false, "", dateChange);

    //初始化时间类型combobox，并加载数据
    $("#sjtype").combobox({
        width: _iWidth100,
        listWidth: _iWidth100,
        valueField: "dm",
        textField: "mc",
        editable: false,
        panelHeight: 102,
        onSelect: function () {
            var newValue = $(this).combobox("getValue");
            dateExtentCalculation(newValue, "sdate", "edate");
        },
        enterDown: function () {
            var newValue = $(this).combobox("getValue");
            dateExtentCalculation(newValue, "sdate", "edate");
        }
    });
    var options = [{ dm: "本月", mc: "本月" }, { dm: "上一月", mc: "上一月" }, { dm: "过去三个月", mc: "过去三个月" }, { dm: "近半年", mc: "近半年" }, { dm: "本年", mc: "本年"}];
    $("#sjtype").combobox("loadData", options);

    //初始化发票类型combobox，并加载数据
    $("#fptypebh").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        editable: false,
        panelHeight: 82,
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部") {
                $(this).combobox("setText", "");
            }
        }
    });
    $("#fptypebh").combobox("loadData", [{ "dm": "", "mc": "全部" }, { "dm": "0", "mc": "未抵扣" }, { "dm": "1", "mc": "已抵扣" }, { "dm": "2", "mc": "已退票"}]);

    //初始化供应商combobox并加载数据
    $("#gysdmP0401").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部供应商") {
                $(this).combobox("setText", "");
            }
        }
    });
    var gyslist = getComboboxData("Tgysxx2");
    gyslist.unshift({ "dm": "", "mc": "全部供应商" });
    $("#gysdmP0401").combobox("loadData", gyslist);

    //初始化发票编号combobox并加载数据
    $("#fpbh").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部发票") {
                $(this).combobox("setText", "");
            }
        },
        onChange: function (newValue) {
            fpbh = newValue;
        }
    });


    //设置供应商、发票编号、发票类型、时间类型combobox初始值
    $("#gysdmP0401,#fptypebh").combobox("setValue", "");
    $("#sjtype").combobox("setValue", "本月");
    dateExtentCalculation("本月", "sdate", "edate");

    bLoadComplete = true;
    $(".layoutpanel").css("z-index", "50000009");
    options = gyslist = s = null;
}

//日期范围修改方法
function dateChange() {
    if ($("#sjtype").combobox("getText") != "自定义") {
        $("#sjtype").combobox("setValue", "");
        $("#sjtype").combobox("setText", "自定义");
    }
}

//双击数据行后要执行的动作
function ondblclickRow(altertype, rowId) {
    var selItem = $(this).getRowData(rowId);
    if (selItem.djbh) {
        switch (selItem.zt) {
            case "已抵扣":
            case "已退票":
                showWh(rowId);
                break;
            case "未抵扣":
                openWh(rowId);
                break;
        }
    }
}

//为管理页面绑定事件
function bindGridEventP0401() {
    $("#" + strTableP0401).setGridParam({

        //设置浮动按钮
        onSelectRow: function (rowId) {
            try {
                selRowId = rowId;
                var selItem = $(this).getRowData(rowId);
                if (selItem.djbh) {
                    var strBtns = "";
                    switch (selItem.zt) {
                        case "已抵扣":
                            strBtns = '<a  onclick="showWh(' + rowId + ');return false; ">查看</a>-<a  onclick="openDk(' + rowId + ');return false; ">抵扣</a>-<a  onclick=" changeZtP0401(' + rowId + ',1);return false; ">取消抵扣</a>';
                            break;
                        case "未抵扣":
                            strBtns = '<a  onclick="openDk(' + rowId + ');return false; ">抵扣</a>-<a  onclick="openTp(' + rowId + ');return false; ">退票</a>-<a  onclick="openWh(' + rowId + ');return false; ">修改</a>-<a onclick="delRowDataP0401(' + rowId + ');return false; ">删除</a>';
                            break;
                        case "已退票":
                            strBtns = '<a  onclick="showWh(' + rowId + ');return false; ">查看</a>-<a  onclick=" openTp(' + rowId + ');return false; ">退票</a>-<a  onclick=" changeZtP0401(' + rowId + ',2);return false; ">取消退票</a>';
                            break;
                    }
                    createFloatButton.call(this, rowId, strBtns);
                }
            } catch (e) { }
        },
        onSortCol: function (index, colindex, sortorder) {
            try {
                searchParam.sortfield = index;
                searchParam.orderby = sortorder;
                loadGridData_Page(searchParam);
                $("div.operate").hide();
                return "stop";
            } catch (e) { }
        }
    });
}

//查询按钮的方法
function searchDataClick_P0401(flag) {
    try {
        var sdate = $("#sdate").val();
        var edate = $("#edate").val();
        var gysdm = $("#gysdmP0401").combobox("getValue");
        var fpbh = $("#fpbh").combobox("getValue");
        var fptypebh = $("#fptypebh").combobox("getValue");

        if (gysdm == undefined) { $("#gysdmP0401").combobox("setValue", ""); gysdm = ""; }
        if (fpbh == undefined) { $("#fpbh").combobox("setValue", ""); fpbh = ""; }

        if (flag == 1) {
            searchParam.sortfield = "djdate";
            searchParam.orderby = "desc";
        }
        searchParam.flag = flag;
        searchParam.where = '"sdate":"' + sdate + '","edate":"' + edate + '","gysdm":"' + gysdm + '","zt":"' + fptypebh + '","fpbh":"' + fpbh + '"';
        var s = loadGridData_Page(searchParam);
        searchParam.flag = 0;
        if (s.Records.length == 0) {
            s.je = "&nbsp;";
        }
        $("#" + strTableP0401).footerData("set", { rn: "合计", a1: s.je }, true);
        s = null;
    } catch (e) { }
}

//删除管理界面的数据
function delRowDataP0401(rowId) {
    try {
        var delItem = $("#" + strTableP0401).getRowData(rowId);
        window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
            if (msgBox.dlgRst.Yes == strRet) {
                if (delItem.glsl > 0) {
                    window.parent.cihoAlert(msg.del.delForbid, msgBox.dlgBtn.Ok);
                } else {
                    var s = ParseData(window.external.DoOptions(strTableP0401, "Delete", '{"djbh":"' + delItem.djbh + '"}'));
                    if (s && s.ReturnCode == 0) {
                        refreshFPBH("");
                        searchDataClick_P0401(2);
                    } else {
                        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                    }
                }
            }
        });
    } catch (e) { }
}

//改变管理界面的发票状态
function changeZtP0401(rowId, bz) {
    try {
        var item = $("#" + strTableP0401).getRowData(rowId);
        var s = ParseData(window.external.DoOptions(strTableP0401, "DoOthers", '{"djbh":"' + item.djbh + '","zt":"0","bz":"' + bz + '"}'));
        if (s.ReturnCode == 0) {
            $("#" + strTableP0401).setCell(rowId, "zt", "0");
        } else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
    } catch (e) { }
    item = s = null;
}

//========================窗口公共方法====================

//创建单据grid
function createDjGrid(strTableName, cNames, cModel) {
    $("#" + strTableName).jqGrid({
        datatype: "local",
        //height: "100%",
        autowidth: true,
        colNames: cNames,
        colModel: cModel,
        rownumbers: true,
        footerrow: true,
        sortable: false,
        rownumWidth: 30,
        cellEdit: true,
        cellsubmit: "clientArray"
    });
}

//初始化表单元素的属性和事件
function initInputsProp(dlgId) {
    //设置单据时间、发票日期、开票单位、发票金额、备注的宽度
    $("#djdate,#fprq,#a1", "#" + dlgId).parent().addClass("inp_70");
    $("#kpdwmc", "#" + dlgId).parent().addClass("inp_150");
    $("#bz", "#" + dlgId).parent().addClass("bz");

    //初始化开票单位combobox，并加载数据
    $("#kpdwmc", "#" + dlgId).combobox({ valueField: "dm", textField: "mc" });
    var kpdwList = getComboboxData("Tkpdwxx");
    kpdwList.push({ "mc": "<font color='red'>添加收票单位</font>", "dm": "-1" });
    $("#kpdwmc", "#" + dlgId).combobox("loadData", kpdwList);

    //初始化供应商combobox，并加载数据
    $("#gysmc", "#" + dlgId).combobox({
        valueField: "dm",
        textField: "mc",
        onSelect: function (item) {
            if (item.dm == "-1") {
                ciho.IniData({ id: "divAddType", title: "供应商", table: "Tflxx" }, { model: "Tgysxx", jquery: $(this) });
                $(this).combobox("setValue", "");
            } else {
                var kpdw = ParseData(window.external.DoOptions(strTableP040101, "DoOthers", '{"gysdm":"' + item.dm + '","fb":"1"}'));
                if (kpdw.ReturnCode == 0 && kpdw.kpdwdm) {//跟踪成功
                    $("#kpdwmc", "#" + dlgId).combobox("setValue", kpdw.kpdwdm);
                    $("#kpdwmc", "#" + dlgId).combobox("setText", kpdw.kpdwmc);
                }
            }
        },
        afterChange: function (newValue, newText) {
            if (newValue == "-1") {
                ciho.IniData({ id: "divAddType", title: "供应商", table: "Tflxx" }, { model: "Tgysxx", jquery: $(this) });
                ciho.showTypeDialog();
                $(this).combobox("setValue", "");
            }
        }
    });
    var gyslist = getComboboxData("Tgysxx");
    gyslist.push({ "mc": "<font color='red'>添加供应商</font>", "dm": "-1" });
    $("#gysmc", "#" + dlgId).combobox("loadData", gyslist);


    //为单据时间、发票日期、发票金额、供应商、开票单位、发票编号、收票日期、备注绑定事件
    inputAndBindData("djdate", false, "#" + dlgId, function () { $("#" + dlgId).data("change", true); });
    inputAndBindData("fprq", false, "#" + dlgId, function () { $("#" + dlgId).data("change", true); });
    $("#a1", "#" + dlgId).autoNumeric({ mDec: window.parent.strPricePlace, aSep: "", mNum: 9 }).focus(function () { this.select(); }).css("ime-mode", "disabled");
    $("#gysmc", "#" + dlgId).combobox({ onChange: function () { $("#" + dlgId).data("change", true); } });
    $("#kpdwmc", "#" + dlgId).combobox({
        onChange: function () { $("#" + dlgId).data("change", true); },
        onSelect: function (item) {
            if (item.dm == "-1") {
                ciho.IniData({ id: "divAddType", title: "收票单位", table: "Tflxx" }, { model: "Tkpdwxx", jquery: $(this) });
                $(this).combobox("setValue", "");
            }
        },
        afterChange: function (newValue, newText) {
            if (newValue == "-1") {
                ciho.IniData({ id: "divAddType", title: "收票单位", table: "Tflxx" }, { model: "Tkpdwxx", jquery: $(this) });
                ciho.showTypeDialog();
                $(this).combobox("setValue", "");
            }
        }
    })
    $("#djdate,#fprq,#bz,#fpbh", "#" + dlgId).focus(function () { this.select(); });
    $("#djdate,#fprq,#a1,#bz,#sfzjgp,#fpbh", "#" + dlgId).change(function () { $("#" + dlgId).data("change", true); });
    $("#fpbh", "#" + dlgId).keypress(function (event) {
        event.keyCode = event.keyCode || event.charCode;
        if (String.fromCharCode(event.keyCode) == "'") { return false; }
        if (String.fromCharCode(event.keyCode) == "\"") { return false; }
    });
    gyslist = kpdwList = null;
}

//关闭窗口
function closeMyDlg(dlgId, strType, tbId) {
    try {
        var isChange = $("#" + dlgId).data("change");
        if (isChange) {
            window.parent.cihoAlert(msg.other.haveChange, msgBox.dlgBtn.YesNoCancel, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    saveMyData(dlgId, 1, tbId);
                }
                else if (msgBox.dlgRst.No == strRet) {
                    cihoDlgClose(dlgId);
                }
            }
        );
        } else {
            cihoDlgClose(dlgId);
        }
    } catch (e) { }
}

//为grid的列添加格式化函数
function addColFormater(tbId) {
    var $tbId = $("#" + tbId);
    $tbId.setColProp("sl", { formatter: formatCountPlace });
    $tbId.setColProp("a2", { formatter: formatPricePlace });
    $tbId.setColProp("je", { formatter: formatMoneyPlace });
    $tbId.setColProp("spmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
}

//格式化百分号
function formatPercentPlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return (cellValue * 100).toFixed(window.parent.strPercentPlace) + "%";
    }
    else {
        return "&nbsp;";
    }
}
//取消格式化百分号
function unformatPercentPlace(cellValue, options, rowObject) {
    if (/\d+%$/.test(cellValue)) {
        return cellValue.replace("%", "");
    }
    else {
        return "&nbsp;";
    }
}

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

//格式化价格
function formatPricePlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strPricePlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式化金额
function formatMoneyPlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}
//格式化grid中的combobox
function my_input(value, options) {
    return $('<select name="' + options.name + '" id="' + options.id + '"></select>').addClass("easyui-combobox");
}
function my_value(ele) {
    return ele.combobox('getText');
}

//加载窗口grid数据，并计算合计
function loadGridData(tbId, mylist) {
    var count = mylist.length > 5 ? mylist.length : 5;
    //添加行并为行分配id，并计算合计
    var hjje = 0, $tbId = $("#" + tbId);
    for (var i = 0; i < count; i++) {
        if (mylist[i]) {                                                                         //添加后台数据行
            hjje += isNaN(mylist[i].je) ? 0 : parseFloat(mylist[i].je);
            $tbId.addRowData(i + 1, mylist[i]);      //添加后台数据行
        }
        else {                                                                                     //添加空行
            $tbId.addRowData(i + 1, {});
        }
    }
    $tbId.footerData("set", { rn: "合计", je: hjje }, true);
    $tbId.data("nextNum", count + 1);
    resizeGridScroll(tbId); 
    $tbId = null;
}

//添加空行
function addNewRow(tbId) {
    try {
        var $tbId = $("#" + tbId);
        var nextNum = $tbId.data("nextNum") + 1;
        $tbId.addRowData(nextNum, {});
        $tbId.data("nextNum", nextNum);
        resizeGridScroll(tbId);
    } catch (e) { }
}

//删除窗口中的grid数据
function delDjRow(tbId, rowId) {
    try {
        $("#" + tbId).saveCell(cellX, cellY);
        var delItem = $("#" + tbId).getRowData(rowId);
        var vCols = $("#" + tbId).data("vCols");

        if (delItem.flag && !isRowEmpty(delItem, vCols)) {//如果有商品代码
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    if (delItem.glsl > 0) {
                        window.parent.cihoAlert(msg.del.delForbid, msgBox.dlgBtn.Ok);
                    } else {
                        var $grid = $("#" + tbId);
                        if (delItem.mxguid) {
                            var records = $("#" + tbId).data("records");
                            records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                            $grid.data("records", records);
                            changeZt(tbId);
                        }
                        $grid.delRowData(rowId);
                        sumGridTotal(tbId);
                        resizeGridScroll(tbId);
                    }
                }
            });
        }
        else {
            $("#" + tbId).delRowData(rowId);
            if (delItem.mxguid) {                                   //如果存在mxguid则保持到records数组里
                var records = $tbId.data("records");
                records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                $tbId.data("records", records);
                changeZt(tbId);                                      //改变窗口的状态
            }
            sumGridTotal(tbId);
            resizeGridScroll(tbId);
        }

    } catch (e) { }
}

//保存单据，
//afterSave：1：保存退出
//                  2：保存增加
//tbId：        1：抵扣：Tp040101
//                  2：抵扣：Tp040102
function saveMyData(dlgId, afterSave, tbId) {
    try {
        //添加分类
        if (tbId == ciho.layal.table) {
            ciho.saveType(); return;
        }
        if (tbId == strTableP040101) {
            saveP040101(tbId, afterSave, dlgId); return;
        }
        if (tbId == strTableP040102) {
            saveP040102(tbId, afterSave, dlgId); return;
        }
        if (tbId == strTableP040103) {
            saveP040103(tbId, afterSave, dlgId); return;
        }
    } catch (e) { }
}

//计算grid脚部合计
function sumGridTotal(tbId) {
    var ypje = 0, $tbId = $("#" + tbId);
    var ids = $tbId.getDataIDs();
    for (var i = 0, len = ids.length; i < len; i++) {
        var item = $tbId.getRowData(ids[i]);
        ypje += isNaN(item.je) ? 0 : item.je * 1;
    }
    $tbId.footerData("set", { rn: "合计", je: ypje }, true);
}

//改变对话框或数据行的状态
//如果只提供表格id，则只改变窗口的状态标志
function changeZt(tbId, rowId) {
    if (tbId == strTableP040101) {
        $("#" + strDivP040101).data("change", true);
    } else {
        $("#" + strDivP040102).data("change", true);
    }
    if (rowId) {
        var $tbId = $("#" + tbId);
        var item = $tbId.getRowData(rowId);
        if (item.mxguid) {
            $tbId.setCell(rowId, "flag", 2);                               //2代表更新
        } else {
            $tbId.setCell(rowId, "flag", 1);                               //1代表新增
        }
        $tbId = item = null;
    }
}

//========================公共方法========================
function refreshMyCombobox(strModels) {
    for (var i = 0; i < strModels.length; i++) {
        var data;
        //这里是当前页面有的comgbobox
        if (strModels[i] == "Tgysxx") {
            data = getComboboxData(strModels[i] + "2");
            data.unshift({ dm: "", mc: "全部供应商" });
            reLoadCombobox("gysdmP0401", data);
        }
    }
}



//判断grid中某一行是否为空行
function isRowEmpty(row, cols) {
    for (var i = 0; i < cols.length; i++) {
        if (!/^\s*$/.test(row[cols[i]])) {
            return false;
        }
    }
    return true;
}

function refreshFPBH(val) {
    var s = ParseData(window.external.DoOptions(strTableP0401, "GetComboBoxData", "{}"));
    if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
        s.Records.unshift({ "dm": "", "mc": "全部发票" });
        $("#fpbh").combobox("loadData", s.Records);
    }
    $("#fpbh").combobox("setValue", val);
}