var iseditable = true;

//打开抵扣单
function openDk(rowId) {
    try {
        iseditable = true;
        var dlgId = strDivP040102, tbId = strTableP040102;

        creatDiv_ShowDlgHaveTbl(dlgId, "进项发票抵扣", false, true, tbId, 700);               //创建弹出窗口
        var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));      // 向后台请求配置信息
        var header = createInputs(config.pageHeader);                                        // 根据头配置 生成表单元素 

        //将生产的表单元素添加到dialog中
        $("#" + dlgId + "_divform").append(header).append('<table id="' + tbId + '"></table>');

        //创建jqgrid
        createDjGrid(tbId, config.colNames, config.colModel);

        var $dlgId = $("#" + dlgId);

        $("table.ui-jqgrid-htable th:first", $dlgId).text("序号");

        //为jqgrid绑定事件
        initGridSetP040102(tbId, dlgId);


        //设置抵扣日期的宽度并绑定日期控件
        $("#dkdate", $dlgId).focus(function () { this.select(); }).parent().addClass("inp_70");
        inputAndBindData("dkdate", false, $dlgId, function () { $("#" + dlgId).data("change", true); });

        //初始化开票单位，并加载数据
        $("#kpdwmc", $dlgId).combobox({
            width: _iWidth100,
            valueField: "dm",
            textField: "mc",
            onSelect: function (option) {
                if (option.dm == "-1") {
                    ciho.IniData({ id: "divAddType", title: "开票单位", table: "Tflxx" }, { model: "Tkpdwxx", jquery: $(this) });
                    $(this).combobox("setValue", "");
                }
                //这里执行选择后的动作，更新grid里面的数据
                var s = ParseData(window.external.DoOptions(tbId, "GetList", '{"kpdwdm":"' + option.dm + '","fb":"1"}'));
                if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
                    $("#" + tbId).clearGridData();
                    loadGridData(tbId, s.Records);
                    $("#" + dlgId).data("change", true);
                } else {
                    window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                }
            },
            afterChange: function (newValue, newText) {
                if (newValue == "-1") {
                    ciho.IniData({ id: "divAddType", title: "开票单位", table: "Tflxx" }, { model: "Tkpdwxx", jquery: $(this) });
                    ciho.showTypeDialog();
                    $(this).combobox("setValue", "");
                }
            }
        });
        var kpdwlist = getComboboxData("Tkpdwxx");
        kpdwlist.push({ "mc": "<font color='red'>添加开票单位</font>", "dm": "-1" });
        $("#kpdwmc", $dlgId).combobox("loadData", kpdwlist);

        var mylist = [];
        if (rowId) {                                        //如果有rowId，则为修改
            var item = $("#" + strTableP0401).getRowData(rowId);
            if (item.zt == "已抵扣") {                      //进入抵扣修改（已抵扣）
                $dlgId.data("state", 2);

                //去后台请求修改抵扣信息
                var s = ParseData(window.external.DoOptions(tbId, "GetList", '{"djbh":"' + item.djbh + '","fb":"2"}'));
                if (s && s.ReturnCode == 0 && s.Records instanceof Array && s.Records.length > 0) {
                    mylist = s.Records;
                    $("#dkdate", $dlgId).attr("disabled", true).val(s.Records[0].dkdate);
                } else {
                    window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                }
            } else {                                        //进入添加抵扣（未抵扣）未抵扣
                iseditable = false;
                $dlgId.data("state", 1);

                //去后台请求添加抵扣信息
                var s = ParseData(window.external.DoOptions(tbId, "GetList", '{"kpdwdm":"' + item.kpdwdm + '","djbh":"' + item.djbh + '","fb":"3"}'));
                if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
                    mylist = s.Records;
                } else {
                    window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                }
                $("#dkdate", $dlgId).val(getNowDate());

            }

            //为开票单位信息赋值
            var $kpdw = $("#kpdwmc", $dlgId);
            $kpdw.combobox("setValue", item.kpdwdm);
            if ($kpdw.combobox("getText") == item.kpdwdm) {
                $kpdw.combobox("setText", item.kpdwmc);
            }
            $kpdw.combobox("disable");
            $dlgId.data("data", { kpdwmc: item.kpdwmc, kpdwdm: item.kpdwdm });
            $kpdw = null;
        } else {                                           //新增默认值
            $dlgId.data("data", {});
            $dlgId.data("state", 1);
            $("#dkdate", $dlgId).val(getNowDate());
        }

        //加载jqgrid数据
        loadGridData(tbId, mylist);
        $dlgId.data("change", false);
        $(".layoutpanel").css("z-index", "50000009");
        $dlgId = null;
    } catch (e) { }
}

//初始化grid事件
function initGridSetP040102(tbId, dlgId) {
    var $tbId = $("#" + tbId);
    $tbId.setGridParam({

        //在保存单元格数据之前将抵扣税率转化成小数
        "beforeSaveCell": function (rowId, cellname, value, iRow, iCol) {
            if (cellname == "dksl") { return value / 100; }
        },

        //保存抵扣税率之后求抵扣额
        "afterSaveCell": function (rowId, cellname, value) {
            try {
                if (cellname == "dksl") {
                    if (value * 1) {
                        var data = $("#" + dlgId).data("data");

                        // 为开票单位combobox赋值
                        var $kpdw = $("#kpdwmc", "#" + dlgId);
                        var kpdwdm = $kpdw.combobox("getValue");
                        var kpdwmc = $kpdw.combobox("getText");
                        if (!kpdwdm && (kpdwmc == data.kpdwmc)) { kpdwdm == data.kpdwdm; }

                        //根据开票单位代码去后台请求基本信息中的抵扣税率
                        var s = ParseData(window.external.DoOptions(tbId, "DoOthers", '{"kpdwdm":"' + kpdwdm + '","bz":"1"}'));
                        if (s && s.ReturnCode == 0) {
                            if (value != s.dksl) {
                                window.top.cihoAlert("是否要更改基本信息中的抵扣税率？", msgBox.dlgBtn.YesNo, function (strRet) {
                                    if (msgBox.dlgRst.Yes == strRet) {

                                        //将修改后的抵扣税率保存为基本信息中的抵扣税率
                                        var ss = ParseData(window.external.DoOptions(tbId, "DoOthers", '{"kpdwdm":"' + kpdwdm + '","dksl":"' + value + '","bz":"2"}'));
                                        if (ss && ss.ReturnCode != 0) {
                                            window.top.cihoAlert(ss.MSG, msgBox.dlgBtn.Ok);
                                        }
                                        changePageZt("p0401", "1");
                                    }
                                });
                            }
                        }
                    }

                    //去发票金额，对抵扣额求值
                    var fpje = $(this).getCell(rowId, "a1");
                    $(this).setCell(rowId, "je", fpje * value);
                    sumGridTotal(this.id);
                }
            } catch (e) { }
        },

        //点击抵扣税率，进入编辑状态
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            try {

                cellX = iRow; cellY = iCol;
                var value = (value * 100).toFixed(window.parent.strPercentPlace);
                var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                switch (cellname) {
                    case "zt":                                      //是否抵扣

                        var state = $("#" + dlgId).data("state");   //如果已经抵扣或者改行没有数据或者不允许编辑，则该单元格不允许进入编辑状态
                        if (state == 2 || !$(this).getCell(rowId, "djbh") || !iseditable) {
                            $(this).restoreCell(iRow, iCol); return;
                        }
                        item.combobox({
                            valueField: "dm",
                            textField: "mc",
                            width: _iWidth80,
                            panelHeight: 42,
                            editable: false,
                            onSelect: function (option) {
                                //是否抵扣
                                var $tbId = $("#" + tbId);
                                if (option.dm == "true") {
                                    $tbId.setCell(rowId, "cz", "true");
                                    var data = $("#" + dlgId).data("data");

                                    //对开票单位赋值
                                    var $kpdw = $("#kpdwmc", "#" + dlgId);
                                    var kpdwdm = $kpdw.combobox("getValue");
                                    var kpdwmc = $kpdw.combobox("getText");
                                    if (!kpdwdm && (kpdwmc == data.kpdwmc)) {
                                        kpdwdm == data.kpdwdm;
                                    }

                                    //根据开票单位去后台请求抵扣税率
                                    var s = ParseData(window.external.DoOptions(tbId, "DoOthers", '{"kpdwdm":"' + kpdwdm + '","bz":"1"}'));
                                    if (s && s.ReturnCode == 0) {
                                        $tbId.setCell(rowId, "dksl", s.dksl);
                                        var fpje = $tbId.getCell(rowId, "a1");
                                        $tbId.setCell(rowId, "je", s.dksl * fpje);
                                    }
                                } else {

                                    //如果不抵扣则全部赋为空
                                    $tbId.setCell(rowId, "cz", "false");
                                    $tbId.setCell(rowId, "dksl", null);
                                    $tbId.setCell(rowId, "je", null);
                                }
                                $("#" + dlgId).data("change", true);
                                sumGridTotal(tbId);
                            }
                        });

                        //加载是否抵扣数据
                        var dplist = [{ dm: "true", mc: "是" }, { dm: "false", mc: "否"}];
                        item.combobox("loadData", dplist);
                        var v = $(this).getCell(rowId, "cz");
                        item.combobox("setValue", v);
                        item.combobox('focus');
                        break;
                    case "dksl":
                        var v = $(this).getCell(rowId, "cz");
                        if (!v || v == "false") {                   //如果是否抵扣为否，则抵扣税率不能进入编辑状态
                            $(this).restoreCell(iRow, iCol); return;
                        }
                        if (isNaN(value)) { item.val(""); } else { item.val(value); }
                        item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                        item.bind("change", function () { $("#" + dlgId).data("change", true); });
                        break;
                }
                $(".layoutpanel").css("z-index", "50000009");
            } catch (e) { }
        }
    });

    //格式化jqgrid
    $tbId.setColProp("dksl", { formatter: formatPercentPlace, unformat: unformatPercentPlace });
    $tbId.setColProp("je", { formatter: formatMoneyPlace });
    $tbId.setColProp("a1", { formatter: formatMoneyPlace });
    $tbId.setColProp("zt", { editoptions: { custom_element: my_input, custom_value: my_value} });
    $tbId.setGridHeight(141);
    $tbId = null;
}

//保存抵扣单
function saveP040102(tbId, afterSave, dlgId) {
    try {
        var $tbId = $("#" + tbId), $dlgId = $("#" + dlgId);
        $tbId.saveCell(cellX, cellY);

        //验证单据信息
        if (!authP040102(tbId, dlgId)) { return false; }

        var state = $("#" + dlgId).data("state");
        var records = [];
        var dkdate = $("#dkdate", $dlgId).val();
        var ids = $tbId.getDataIDs();

        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.djbh && item.cz == "true") {
                var record = '{"djbh":"' + item.djbh + '","dkdate":"' + dkdate + '","a1":"' + item.dksl + '","a2":"' + item.je + '"}';
                records.push(record);
            }
        }

        if (records.length == 0) {
            window.parent.cihoAlert("单据不能为空！", msgBox.dlgBtn.Ok);
            return false;
        }

        var s;
        if (state == 1) {
            //新增抵扣
            s = ParseData(window.external.DoOptions(tbId, "Add", '{"Records":[' + records + ']}'));
        } else {
            //修改保存
            s = ParseData(window.external.DoOptions(tbId, "Edit", records.toString()));
        }

        if (s.ReturnCode == 0) {                            //添加成功！
            if (afterSave == 2) {                           //保存新增
                resetGrid(tbId, dlgId);
            } else {                                        //保存退出
                cihoDlgClose(dlgId);
            }
            searchDataClick_P0401(0);
        }
        else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
    } catch (e) { }
}

//验证抵扣单
function authP040102(tbId, dlgId) {
    try {
        var amount = $("#" + tbId).footerData("get").je * 1;
        var maxAmount = window.top._MaxPerBill;
        if (amount >= maxAmount) {
            window.parent.cihoAlert("单据金额过大！", msgBox.dlgBtn.Ok);
            //alert("单据金额过大！");
            return false;
        }

        //验证时间
        var djdata = $("#dkdate", "#" + dlgId).val();
        if (!djdata) {
            window.parent.cihoAlert("请输入抵扣日期！", msgBox.dlgBtn.Ok, function () { $("#dkdate", "#" + dlgId).focus(); });
            return false;
        } else {
            var djdt = djdata.replace(/\-/g, "/");
            if (djdt < window.top._startDate) {
                window.parent.cihoAlert(msg.other.dkrqExtent, msgBox.dlgBtn.Ok, function () { $("#dkdate", "#" + dlgId).focus(); });
                return false;
            }
        }

        var $dlgId = $("#" + dlgId);
        var data = $dlgId.data("data");

        //验证收票单位
        var $kpdw = $("#kpdwmc", $dlgId);
        var kpdwdm = $kpdw.combobox("getValue");
        var kpdwmc = $kpdw.combobox("getText");
        if (!kpdwdm && kpdwmc != data.kpdwmc) {
            window.parent.cihoAlert("收票单位为空或不存在！", msgBox.dlgBtn.Ok, function () {
                $kpdw.combobox("focus");
                $dlgId = $kpdw = null;
            });
            return false;
        }

        //验证抵扣税率
        var $tbId = $("#" + tbId);
        var ids = $tbId.getDataIDs();
        for (var i = 0, len = ids.length; i < len; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.djbh && item.cz == "true") {
                if (isNaN(item.dksl) || !item.dksl * 1) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + "】行的抵扣税率为空或零！", msgBox.dlgBtn.Ok); //alert("请输入第【" + (i + 1) + "】行的抵扣税率！");
                    $dlgId = $kpdw = $tbId = null;
                    return false;
                }
            }
        }
        return true
    } catch (e) { }
}

//格式化百分号
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("%", "") / 100;
    }
    else {
        return "&nbsp;";
    }
}
