<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LossForm.aspx.cs" Inherits="Medical.MBusiness.SysLoss.LossForm" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="../../css/style.css" rel="stylesheet" type="text/css" />
    <link href="../../css/bill.css" rel="stylesheet" type="text/css" />
    <link href="../../css/autocomplete.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.ajaxQueue.js" type="text/javascript"></script>
    <script src="../../Scripts/My97DatePicker/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
    <script src="../../js/myLib/autoComplete.js" type="text/javascript"></script>
    <script src="../../Scripts/json2.js" type="text/javascript"></script>
    <script src="../../js/myLib/helper.js" type="text/javascript"></script>
    <script src="../../js/myLib/jsHelper_Form.js" type="text/javascript"></script>
</head>
<body>
    <div class="pt-bill">
        <form id="billForm" name="billForm">
            <table class="pt-bill-frm" >
                <tr>
                    <td colspan="6" class="pt-bill-frm-title">药品损耗</td>
                </tr>
                <tr>
                    <th>损耗单号[*]:</th>
                    <td><input type="text" id="lNum" name="lNum" runat="server"/></td>
                    <th>损耗仓库[*]:</th>
                    <td><select id="lWarehouse" name="lWarehouse" runat="server"></select></td>
                    <th>处理日期[*]:</th>
                    <td><input type="text" id="lDate" name="lDate" runat="server" onclick="WdatePicker()" error="处理日期" checkexpression="NotNull"/></td>
                </tr>
                <tr>
                    <th>损耗原因[*]:</th>
                    <td><input type="text" id="lReason" name="lReason" runat="server" error="损耗原因" checkexpression="NotNull"/></td>
                    <th>经手人[*]:</th>
                    <td><input type="text" id="lMan" name="lMan" runat="server" limit="1"/></td>
                    <th>金额合计[*]:</th>
                    <td><span id="totalMoney" runat="server"></span>元</td>
                </tr>
            </table>
        </form>
        <table id="LossGrid" class="pt-bill-grid" >
            <thead>
                <tr>
                    <td style="width: 40px">行号</td>
                    <td style="width: 70px">药品编码[*]</td>
                    <td style="width: 100px">药品名称</td>
                    <td style="width: 50px">规格</td>
                    <td style="width: 40px">包装单位</td>
                    <td style="width: 40px">剂型</td>
                    <td style="width: 40px">材质</td>
                    <td style="width: 80px">生产企业</td>
                    <td style="width: 70px">批号</td>
                    <td style="width: 80px">有效期</td>
                    <td style="width: 60px">采购价</td>
                    <td style="width: 50px">单价</td>
                    <td style="width: 50px">损耗数量[*]</td>
                    <td style="width: 60px">金额</td>
                    <td style="width: 80px">备注</td>
                    <td style="width: 13px"></td>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
    <div class="pt-line"></div>
    <div class="pt-tip">友情提示：点击第1列行号可对相关记录进行删除操作</div>
    <div class="pt-padding" style="text-align:center">
        <input type="button" id="btnSave" class="pt-button active" value="保存" />
        <input type="button" id="btnClose" class="pt-button active" value="关闭" />
    </div>
    <script>
        (function() {
            var dataSplit = 'Θ ☺ ☻'.split(' '), //单元格、行、表分隔符
            rowCount = 100, //单据行数
            realRow = 1, //实际行数
            url = "LossForm.aspx",
            key = "<%=key %>",
            type = "<%=type %>",
            tdCurrent = null,
            emptyRow = '<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';

            function init() {
                setPage();
                bindEvents();
            }
            function save() {
                if (!JudgeValidate1()) return;
                if (!validateDetails()) return;
                if (!validateDetailsInput()) return;
                if (!validateDetailsAmount()) return;
                endEdit($("#LossGrid tbody"));
                var result = false;
                $.ajax({
                    url: url,
                    type: "POST",
                    data: $.parseJSON(form2JsonString(billForm, { action: "save", details: getDetails(), key: key })),
                    async: false,
                    success: function(data) {
                        result = parseInt(data, 10) > 0;
                    }
                });
                if (result) {
                    top.main.location.reload();
                    top.showTipsMsg('操作成功!', 0, 3000);
                    top.OpenClose('Loss_Form'); //如果写在ajax的success里面报错
                } else {
                    top.showTipsMsg("操作失败，请稍后重试", 1, 4000);
                }
            }
            function validateDetailsInput() {
                //验证是否重复
                var isValidate = true, rowIndex = -1, nextIndex = -1, durgCode = '', batch = '';
                //验证是否有值
                $("#LossGrid tbody tr").each(function() {
                    if ($(this).index() < realRow - 1) {
                        durgCode = $(this).find("td:eq(1) input").val();
                        batch = $(this).find("td:eq(8) input").val();
                        rowIndex = $(this).index() + 1;
                        $("#LossGrid tbody tr").each(function() {
                            nextIndex = $(this).index() + 1;
                            if (rowIndex == nextIndex) return true;
                            if ($(this).index() < realRow - 1) {

                                //编码和批号
                                if (durgCode == $(this).find("td:eq(1) input").val() && batch == $(this).find("td:eq(8) input").val()) {
                                    var error = "第[" + nextIndex + "]行的[药品编码]和[批号]与第[" + rowIndex + "]行的[药品编码]和[批号]重复,请重新选择药品!\n";
                                    isValidate = false;
                                    top.showConfirmMsg(error, function(r) {
                                        if (r) {
                                        }
                                    });
                                    return false;
                                }
                            } else {
                                return false;
                            }
                        });
                    } else {
                        return false;
                    }
                });
                return isValidate;
            }
            function validateDetailsAmount() {
                //验证是否重复
                var isValidate = true;
                $("#LossGrid tbody tr").each(function() {
                    if ($(this).index() < realRow - 1 && !$(this).find("td:eq(12)").html()) {
                        var error = "第[" + ($(this).index()+1) + "]行的[损耗数量]未输入,请点击输入!\n";
                        isValidate = false;
                        top.showConfirmMsg(error, function(r) {
                            if (r) {
                            }
                        });
                        return false;
                    }
                });
                return isValidate;
            }
            function getDetails() {
                //单元格、行、表
                var data = [];
                $("#LossGrid tbody").find("tr").each(function() {
                    if ($(this).find("td:eq(2)").html()) {
                        var row = [], tds = $(this).find("td");
                        row.push(tds[1].innerText); //药品编码
                        row.push(tds[8].innerText); //批号
                        row.push(tds[9].innerText); //有效期
                        row.push(tds[10].innerText); //采购价
                        row.push(tds[11].innerText); //单价
                        row.push(tds[12].innerText); //损耗数量
                        row.push(tds[14].innerText); //备注
                        data.push(row.join(dataSplit[0]));
                    } else {
                        return false;
                    }
                });
                return data.join(dataSplit[1]);
            }
            function validateDetails() {
                //验证是否重复
                var isValidate = true;
                //验证是否有值
                $("#LossGrid tbody").find("input").each(function() {
                    if (!$(this).val() && $(this).parent().parent().index() != realRow - 1 && $(this).attr("error")) {
                        var error = "第" + ($(this).parent().parent().index() + 1) + "行[" + $(this).attr("error") + "]不能为空!\n";
                        isValidate = false;
                        var self = this;
                        top.showConfirmMsg(error, function(r) {
                            if (r) {
                                self.focus();
                            }
                        });
                        return false;
                    }
                });
                return isValidate;
            }
            function addBlankRow(index) {
                if (index + 1 < rowCount) {
                    var td = $("#LossGrid tbody tr:eq(" + (index + 1) + ") td:eq(1)");
                    if (td.children().length == 0) {
                        var input = $('<input type="text" title="可输入条码、名称或简码" />').appendTo(td);
                        bindAutocomplete(input);
                        realRow++;
                    }
                }
                setTrNo();
                calculationEvents();
            }
            function setPage() {
                limit();
                var widths = [];
                $("#LossGrid thead tr td").each(function() {
                    widths.push(getStyle($(this).attr("style"), "width"));
                });

                FixedTableHeader("LossGrid", 300);
                var row = 1, data, html = [];
                if (key !== "") {
                    $.ajax({
                        url: url,
                        data: { action: 'query', key: key },
                        async: false,
                        success: function(rs) {
                            data = eval('(' + rs + ')');
                        }
                    });
                    for (var i = 0, k = data.Rows.length; i < k; i++) {
                        var list = data.Rows[i];
                        html.push('<tr><td></td>');
                        html.push('<td><input type="text" error="药品编码" title="可输入条码、名称或简码" value="' + list.llCode + '" /></td>');
                        html.push('<td>' + list.dName + '</td>');
                        html.push('<td>' + list.dSpec + '</td>');
                        html.push('<td>' + list.dSubsection + '</td>');
                        html.push('<td>' + list.dType + '</td>');
                        html.push('<td>' + list.dMaterial + '</td>');
                        html.push('<td>' + list.dFactory + '</td>');
                        html.push('<td>' + list.llBatch + '</td>');
                        html.push('<td>' + list.llValid + '</td>');
                        html.push('<td>' + list.llPurchasePrice + '</td>');
                        html.push('<td>' + list.llPrice + '</td>');
                        html.push('<td>' + list.llAmount + '</td>');
                        html.push('<td>' + list.llMoney + '</td>');
                        html.push('<td><input type="text" value="' + list.llRemark + '" /></td></tr>');

                        row++;
                        realRow++;
                    }
                }
                for (var i = row; i <= rowCount; i++) {
                    html.push(emptyRow);
                }
                $("#LossGrid tbody").append(html.join(""));
                $("#LossGrid tbody tr td").each(function() {
                    $(this).width(widths[$(this).index()]);
                });
                var input = $('<input type="text" error="药品编码" title="可输入条码、名称或简码" />').appendTo($("#LossGrid tbody tr:eq(" + (row - 1) + ") td:eq(1)"));

                bindAutocomplete($("#LossGrid tbody tr").find("td:eq(1) input"));
                setTrNo();
                if (type == "view") { //查看
                    $("#btnSave").hide();
                    $(".pt-bill").children().find("input").each(function() {
                        $(this).parent().html($(this).val());
                    });
                    $(".pt-bill").children().find("select").each(function() {
                        $(this).parent().html($(this).find("option:selected").text());
                    });
                }
                calculationEvents();
            }
            function calculationEvents() {
                $("#LossGrid tbody input").blur(function() {
                    var td = $(this).parent(), tdIndex = td.index();
                    if (tdIndex == 10 || tdIndex == 12) {
                        calculationMoney(td);
                    }
                });

            }
            //计算金额
            function calculationMoney(td) {
                var tr = td.parent(),
                purchasePrice = 0, //采购价
                amount = 0, //数量
                purchasePriceText = tr.find("td:eq(10)").html(),
                amountText = tr.find("td:eq(12)").children().val(),
                moneyInput = tr.find("td:eq(13)");

                if (purchasePriceText) {
                    purchasePrice = purchasePriceText * 1;
                }
                if (amountText) {
                    amount = amountText * 1;
                }
                moneyInput.html(purchasePrice * amount);
            }
            function setTrNo() {//生成序号
                for (var i = 0; i < rowCount; i++) {
                    $("#LossGrid tbody tr:eq(" + i + ") td:eq(0)").html((i + 1)).attr("title", i < realRow - 1 ? "点击删除该行数据" : "");
                }
            }
            function bindAutocomplete(jqueryObject) {
                var warehouse = $("#lWarehouse option:selected").text();
                jqueryObject.autocomplete("../../MCommon/QueryInventory.ashx?action=getDrug&warehouse=" + escape(warehouse), {
                    title: "barcode",
                    width: 700,
                    thead: [
                        { text: "药品编码", width: 50 },
                        { text: "药品名称", width: 50 },
                        { text: "规格", width: 50 },
                        { text: "单位", width: 50 },
                        { text: "批号", width: 50 },
                        { text: "有效期", width: 50 },
                        { text: "剂型", width: 50 },
                        { text: "材质", width: 50 },
                        { text: "生产企业", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "dCode,dName,dSpec,dSubsection,iBatch,iValid,dType,dMaterial,dFactory";
                    },
                    formatMatch: function(row, i, max) {
                        return "dCode,dName,dSimpleCode";
                    }
                }).result(function(e, row) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.data("data", row);
                    target.val(row.dCode);
                    tr.find('td:eq(2)').html(row.dName);
                    tr.find('td:eq(3)').html(row.dSpec);
                    tr.find('td:eq(4)').html(row.dSubsection);
                    tr.find('td:eq(5)').html(row.dType);
                    tr.find('td:eq(6)').html(row.dMaterial);
                    tr.find('td:eq(7)').html(row.dFactory);
                    tr.find('td:eq(8)').html(row.iBatch);
                    tr.find('td:eq(9)').html(row.iValid);
                    tr.find('td:eq(10)').html(row.iPurchasePrice);
                    tr.find('td:eq(11)').html(row.iPrice);
                    //                    tr.find('td:eq(12)').html('<input type="text" error="损耗数量"/>');
                    tr.find('td:eq(14)').html('<input type="text" />');
                    addBlankRow(tr.index());
                }).removeRelation(function(e) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.data("data", "");
                    target.parent().nextAll().html("");
                });
            }
            function bindEvents() {
                showDetail($("#LossGrid tbody"));
                $("#LossGrid tbody").click(function(e) {
                    var target = $(e.target);
                    if (target.is("td") && target.index() == 0 && target.parent().index() < realRow - 1) {
                        top.showConfirmMsg("确认删除该行数据吗?", function(r) {
                            if (r) {
                                target.parent().remove();
                                //实际行数-1
                                realRow--;
                                $("#LossGrid tbody").append(emptyRow);
                                setTrNo();
                            }
                        });
                    }
                    //
                    if (target.is("td") && target.index() == 12 && target.parent().index() < realRow - 1) {
                        tdCurrent = target;
                        top.openDialog("/MBusiness/SysLoss/inputAmount.aspx?key=" + target.parent().find("td:eq(1) input").val()+"&oldValue="+target.html(), "inputAmount", '损耗数量-编辑', 300, 130, 50, 50, callInputAmountCallBack);
                    }

                });
                $("#btnClose").click(function() {
                    top.OpenClose('Loss_Form');
                });
                $("#btnSave").click(function() {
                    save();
                });
                $("#lWarehouse").change(function() {
                    $("#LossGrid tbody tr").find("td:eq(1) input").unautocomplete();
                    bindAutocomplete($("#LossGrid tbody tr").find("td:eq(1) input"));
                });
            }
            function callInputAmountCallBack() {
                tdCurrent.html(top.art.dialog.data("amount"));
            }
            init();
        })();
    </script>
</body>
</html>
