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

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta name="renderer" content="webkit"/>
    <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge,chrome=1"/>
    <link href="../../css/style.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="../../js/myLib/autoComplete-nocache.js" type="text/javascript"></script>
    <script src="../../Scripts/My97DatePicker/My97DatePicker/WdatePicker.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>
    
    <object id="LODOP_OB" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" style="display:none" >
        <embed id="LODOP_EM" type="application/x-print-lodop" width="0" height="0"></embed>
    </object>
    <script src="../../Scripts/LodopFuncs.js" type="text/javascript"></script>
    <script src="../../js/myLib/Print.js" type="text/javascript"></script>
    <style type="text/css">
    .hidden{display:none}
    .closeIcon{ float:right; margin-right:5px; margin-top:-20px}
    .chooseWindow{ background-color:White;top:10%; left:10%; border:1px solid rgb(107,172,255);position:absolute; display:none;}
    .divData{ overflow:auto; height:315px /*margin:3px;*/}
    .data td,.data th{border:1px solid rgb(122,122,122);height:20px;line-height:20px;outline:none}
    .data th{text-align:center;background-color:rgb(196,222,255)}
    .data tr:hover{ background-color:#DDF4FF}    
    .strongStyle{ display:block; height:20px; letter-spacing:1px; color:White;background-color:rgb(107,172,255)}
    </style>
</head>
<body>
    <table>
        <tr>
            <td colspan="3" class="pt-bill-title">门诊电子处方移动信息系统处方开具</td>
        </tr>
        <tr>
            <td >
                <form id="billForm" name="billForm">
                    <table>
                        <tr>
                            <td>
                                <table class="pt-bill-frm" style="border:2px solid rgb(107,172,255); height:100px">
                                    <tr>
                                        <td><input type="button" id="btnCallHistory" class="pt-button active" value="调用历史处方" /></td>
                                        <td><input type="button" id="btnCreateTemplate" class="pt-button active" value="转为处方模板" />
                                            <input type="button" id="btnCallTemplate" class="pt-button active" value="调用处方模板" /></td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <table class="pt-bill-frm" style="border:2px solid rgb(107,172,255); margin-top:2px; height:390px">
                                    <tr>
                                        <th>门诊号</th>
                                        <td colspan='3'><input type="text" id="wCode" name="wCode" runat="server" class="pt-readonly" /></td>
                                    </tr>
                                    <tr>
                                        <th>处方编号</th>
                                        <td colspan='3'><input type="text" id="wNum" name="wNum" runat="server" class="pt-readonly" /></td>
                                    </tr>
                                    <tr>
                                        <th>开具日期</th>
                                        <td colspan='3'>
                                            <input type="text" id="wDate" name="wDate" runat="server" onclick="WdatePicker()" error="开具日期" checkexpression="NotNull" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>医生</th>
                                        <td colspan='3'><input type="text" id="wDoctor" name="wDoctor" class="pt-readonly" runat="server" /></td>
                                    </tr>
                                    <tr>
                                        <th>科别</th>
                                        <td colspan='3'><input type="text" id="wDepartment" name="wDepartment" class="pt-readonly" runat="server" /></td>
                                    </tr>
                                    <tr>
                                        <th>姓名</th>
                                        <td colspan='2'><input type="text" id="wName" name="wName" runat="server" error="姓名" checkexpression="NotNull"  /></td>
                                        <td><input type="button" id="btnNewPatient" class="pt-button active" value="新增" /></td>
                                     </tr>
                                    <tr> 
                                        <th>性别</th>
                                        <td colspan='3'>
                                            <select id="wSex" style="width:50px" name="wSex" class="pt-readonly" runat="server">
                                                <option value="男">男</option>
                                                <option value="女">女</option>
                                            </select>
                                        </td>
                                     </tr>
                                    <tr> 
                                        <th>年龄</th>
                                        <td>
                                            <input type="text" id="wAge" name="wAge" class="pt-readonly" runat="server" style="width:25px" error="年龄" checkexpression="NotNull"  />
                                            <select id="wAgeUnit" name="wAgeUnit" class="pt-readonly" style="width:40px;border-bottom:none" runat="server">
                                                <option value="岁">岁</option>
                                                <option value="月">月</option>
                                                <option value="天">天</option>
                                            </select>
                                        </td>
                                        <th>体重</th>
                                        <td><input type="text" id="wWeight" name="wWeight" runat="server" style="width:25px" />kg</td>
                                    </tr>
                                    <tr>
                                        <th>住址</th>
                                        <td colspan='3'><input type="text" id="wAddress" name="wAddress" class="pt-readonly" runat="server" /></td>
                                    </tr>
                                    <tr>
                                        <th>过敏史</th>
                                        <td colspan='3'><input type="text" id="wAllergy" name="wAllergy" class="pt-readonly" runat="server" /></td>
                                    </tr>
                                    <tr>
                                        <th>临时诊断</th>
                                        <td colspan='3'>
                                            <textarea id="wDiagnosis" cols="20" rows="3" name="wDiagnosis" runat="server"></textarea>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </form>
            </td>
            <td style="width:690px;">
                <div style="width:690px;height:490px; overflow:auto;border:2px solid rgb(107,172,255)">
                    <table id="WesternGrid" class="pt-bill-grid">
                        <thead>
                            <tr>
                                <td style="width: 40px">行号</td>
                                <td style="width: 150px">药品名称</td>
                                <td style="width: 120px">规格</td>
                                <td style="width: 40px">单位</td>
                                <td style="width: 40px">总量</td>
                                <td style="width: 70px">实用量</td>
                                <td style="width: 210px">用法</td>
                                <td style="width: 80px;display:none">是否注射</td>
                                <td style="width: 80px">批号</td>
                                <td style="width: 80px">有效期</td>
                                <td style="width: 60px">库存数</td>
                                <td style="width: 60px;display:none">单价</td>
                                <td style="width: 40px;display:none">类型</td>
                                <td style="width: 40px;display:none">编码</td>
                                <td style="width:13px"></td>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </td>
            <td style="width:280px;">
                <table>
                    <tr>
                        <td>
                            <table class="pt-bill-frm" style="border:2px solid rgb(107,172,255); height:492px">
                                <tr>
                                    <th>诊疗费</th>
                                    <td><input type="text" id="cGeneral" onkeyup="add()" runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>药品费</th>
                                    <td><input type="text" id="cDrug"  class="pt-readonly"  runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>床位费</th>
                                    <td><input type="text" id="cObserve" runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>检验费</th>
                                    <td><input type="text" id="cInspection"  class="pt-readonly"  runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>检查费</th>
                                    <td><input type="text" id="cInspectionTotal"  class="pt-readonly"  runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>治疗费</th>
                                    <td><input type="text" id="cWesternCure"  class="pt-readonly"   runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>手术费</th>
                                    <td><input type="text" id="cOperation"  class="pt-readonly"   runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>材料费</th>
                                    <td><input type="text" id="cMaterial" onkeyup="add();" runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>其他</th>
                                    <td><input type="text" id="cOther"  class="pt-readonly"  runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>应收合计</th>
                                    <td><input type="text" id="cReceivable"  class="pt-readonly"   runat="server" /></td>
                                </tr>
                                <tr>
                                    <th>实收合计</th>
                                    <td><input type="text" id="cReal"  class="pt-readonly"   runat="server" /></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td colspan='3' class="pt-tip">友情提示：点击第1列行号可对相关记录进行删除操作</td>
        </tr>
        <tr>
            <td colspan='3' style="text-align: center">
                <input type="button" id="btnAdd" class="pt-button active" value="新增" />
                <input type="button" id="btnUpdate" class="pt-button active" value="修改" />
                <input type="button" id="btnPrint" class="pt-button active" value="打印" />
                <input type="button" id="btnSave" class="pt-button active" value="保存" />
                <input type="button" id="btnClose" class="pt-button active"  value="关闭" />
            </td>
        </tr>
    </table>
    <script type="text/javascript">
        (function() {
            var dataSplit = 'Θ ☺ ☻'.split(' '), //单元格、行、表分隔符
            rowCount = 50, //单据行数
            realRow = 1, //实际行数
            url = "WesternForm.aspx",
            key = "<%=key %>",
            type = "<%=type %>",
            emptyRow = '<tr><td style="word-wrap:break-word;overflow:hidden;width: 40px"></td><td style="word-wrap:break-word;overflow:hidden;width: 150px"></td><td style="word-wrap:break-word;overflow:hidden;width: 120px"></td><td style="word-wrap:break-word;overflow:hidden;width: 40px"></td><td style="word-wrap:break-word;overflow:hidden;width: 40px"></td><td style="word-wrap:break-word;overflow:hidden;width: 70px"></td><td style="word-wrap:break-word;overflow:hidden;width: 210px"></td><td style="word-wrap:break-word;overflow:hidden;display:none;width: 80px"></td><td style="word-wrap:break-word;overflow:hidden;width: 80px"></td><td style="word-wrap:break-word;overflow:hidden;width: 80px"></td><td style="word-wrap:break-word;overflow:hidden;width: 80px"></td><td style="word-wrap:break-word;overflow:hidden;display:none;width: 60px"></td><td style="word-wrap:break-word;overflow:hidden;display:none;width: 40px"></td><td style="word-wrap:break-word;overflow:hidden;display:none;width: 40px"></td><td style="display:none"></td></tr>',

            recipeData = "",
            widths = [],
            //totalGroup = 1, //药品不能超过5组
            printModule = new Print({ pageName: "A5" }),
            wNum = "";

            //           $('#cObserve').bind('input propertychange', function() {
            //               alert(this.value);
            //           }).bind('input input', function() {
            //               alert(this.value);
            //           });

            function init() {
                if (type == "view") {
                    $("#btnPrint").show();
                    $("#btnAdd").show();
                } else {
                    $("#btnPrint").hide();
                    $("#btnAdd").hide();
                }
                $("#btnUpdate").hide();

                $(".pt-readonly").focus(function() {
                    this.blur();
                });

                //totalGroup = 1;
                changeButton(true);
                $("#WesternGrid thead tr td").each(function() {
                    widths.push(getStyle($(this).attr("style"), "width"));
                });
                FixedTableHeader("WesternGrid", 445, 935);
                getData();
                loadData();
                bindEvents();
                medicalAutocomplete();
                WesternEvents();
                DiagnosisAutocomplete();
                observeAutocomplete();
            }
            //计算金额
            function loadCost(num) {
                $.get(url, { action: "loadCost", num: num }, function(data) {
                    data = eval('(' + data + ')');
                    for (var i in data.Rows) {
                        var list = data.Rows[i];
                        $("#cAccount").val(list.cAccount);
                        $("#cAccumulate").val(list.cAccumulate);
                        $("#balance").val(list.balance);
                        $("#cGeneral").val(list.cGeneral);
                        $("#cDrug").val(list.cDrug);
                        $("#cObserve").val(list.cObserve);
                        $("#cInspection").val(list.cInspection);
                        $("#cInspectionTotal").val(list.cInspectionTotal);
                        $("#cCure").val(list.cCure);
                        $("#cOperation").val(list.cOperation);
                        $("#cMaterial").val(list.cMaterial);
                        $("#cOther").val(list.cOther);
                        $("#cReceivable").val(list.cReceivable);
                        //$("#cExpenseAccount").val(list.cExpenseAccount);
                        $("#cReal").val(list.cReal);
                        $("#cInspection").val(list.cInspection);
                        $("#cWesternCure").val(list.cCure);
                    }
                });
            }
            function WesternEvents() {
                $('input[type="text"]').on("blur", function() {
                    var index = $(this).parent().index();
                    //countTotal();
                    if (index == 4) {
                        countTotal();
                    }
                });
            }
            function countTotal() {
                var totalMoney = 0; amount = 0; price = 0, totalMoney1 = 0; amount1 = 0; price1 = 0;
                $("#cDrug").val(0);
                $("#cOther").val(0);        
                $("#WesternGrid tbody").find("tr").each(function() {
                    var tds = $(this).find("td"), index = $(this).index();
                        if (tds[4].firstChild) {
                            amount = tds[4].firstChild.value * 1;
                        }
                        price = tds[11].innerText * 1;
                        price = price.toFixed(2);
                        totalMoney += amount * price;                        
                    if (tds[12].innerText == "检查") {
                        if (tds[4].firstChild) {
                            amount1 = tds[4].firstChild.value * 1;
                        }
                        price1 = tds[11].innerText * 1;
                        totalMoney1 += amount1 * price1;                        
                    }
                });
                $("#cDrug").empty();
                $("#cDrug").val((totalMoney-totalMoney1).toFixed(2));
                $("#cOther").empty();
                $("#cOther").val(totalMoney1.toFixed(2));
                add();
            }
            function changeButton(isShow) {
                if (isShow) {
                    $("#btnCallHistory").show();
                    $("#btnCallTemplate").show();
                    $("#btnCreateTemplate").hide();
                    $("#btnSave").show();
                } else {
                    $("#btnCallHistory").hide();
                    $("#btnCallTemplate").hide();
                    $("#btnCreateTemplate").show();
                    $("#btnSave").hide();
                }
            }
            function validatePatient() {
                var isExists = true, rs = 0;
                $.ajax({
                    url: url,
                    data: { action: "validatePatient", name: $("#wName").val() },
                    async: false,
                    success: function(data) {
                        rs = parseInt(data, 10);
                    }
                });
                if (rs == 0) {
                    isExists = false;
                    top.showTipsMsg('[患者姓名]没有添加，请重新选择或者点击[新增]按钮添加信息!', 1, 3000);
                }
                return isExists;
            }
            function save() {
                if (!JudgeValidate1()) return;
                if (!validateDetails()) return;
                if (!validateDetailsInput()) return;
                //验证患者姓名
                if (!validatePatient()) return;
                $("#btnSave").hide();
                endEdit($("#WesternGrid tbody"));
                setIsInjection(); //重复赋值"是否注射"列
                var recipeType = "普通";
                var result = false, codes = [];
                $.ajax({
                    type: "POST",
                    url: url,
                    data: $.parseJSON(form2JsonString(billForm, { action: "save", recipeType: recipeType, details: getDetails(), key: key, general: $("#cGeneral").val(), accumulate: $("#cAccumulate").val(), observe: $("#cObserve").val(), material: $("#cMaterial").val() })),
                    async: false,
                    success: function(data) {
                        data = data.split(dataSplit[1]);
                        result = parseInt(data[0], 10);
                        codes = data[1].split(dataSplit[0]);
                    }
                });
                if (result > 0) {
                    top.showTipsMsg('操作成功!', 0, 3000);
                    $("#wCode").val(codes[0]);
                    $("#wNum").val(codes[1]);
                    wNum = codes[1];
                    loadCost(codes[1]);
                    $("#btnPrint").show();
                    $("#btnAdd").show();
                    $("#btnUpdate").show();
                } else {
                    top.showTipsMsg("操作失败，请稍后重试!", 1, 3000);
                    $("#btnSave").show();
                }
            }
            //验证总量
            function validateDetailsInput() {
                var isValidate = true;
                $("#WesternGrid tbody tr").each(function() {
                    if ($(this).index() < realRow - 1 && $(this).find("td:eq(12)").html() == "药品") {
                        var total = $(this).find("td:eq(4) input").val() * 1, amount = $(this).find("td:eq(10)").html() * 1;
                        if (total > amount) {
                            var error = "第" + ($(this).index() + 1) + "行[总量]不能大于[库存数],请重新选择批次或更改总量!\n";
                            isValidate = false;
                            var self = this;
                            top.showConfirmMsg(error, function(r) {
                                if (r) {
                                }
                            });
                            return false;
                        }
                    } else {
                        return false;
                    }
                });
                return isValidate;
            }
            function getDetails() {
                var data = [];
                $("#WesternGrid tbody").find("tr").each(function() {
                    if ($(this).find("td:eq(1)").html()) {
                        var row = [], tds = $(this).find("td");
                        row.push(tds[1].innerText); //药品名称
                        row.push(tds[2].innerText); //规格
                        row.push(tds[3].innerText); //单位
                        row.push(tds[4].innerText); //总量
                        row.push(tds[5].innerText); //实用量
                        row.push(tds[6].innerText); //用法
                        row.push(tds[7].innerText); //是否注射
                        row.push(tds[8].innerText); //批号
                        row.push(tds[9].innerText); //有效期
                        row.push(tds[11].innerText); //单价
                        row.push(tds[12].innerText); //类型
                        row.push(tds[13].innerText); //编码
                        data.push(row.join(dataSplit[0]));
                    } else {
                        return false;
                    }
                });
                return data.join(dataSplit[1]);
            }
            function validateDetails() {
                //验证是否重复
                var isValidate = true;
                //验证是否有值
                $("#WesternGrid 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 = $("#WesternGrid 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();
                //WesternEvents();
            }
            function getData() {
                if (key !== "") {
                    $.ajax({
                        url: url,
                        data: { action: 'query', key: key },
                        async: false,
                        success: function(rs) {
                            recipeData = rs;
                        }
                    });
                }
            }
            function loadData(callTemplateData) {
                realRow = 1;
                var html = [];
                if (recipeData.length > 0) {
                    recipeData = eval('(' + recipeData + ')');
                    for (var i in recipeData.Rows) {
                        var list = recipeData.Rows[i];         
                        html.push('<tr><td></td>');
                        html.push('<td><input type="text" error="药品名称" title="可输入诊疗项目、条码、名称或简码" value="' + list.wName + '" /></td>');
                        html.push('<td>' + list.wSpec + '</td>');
                        html.push('<td>' + list.wUnit + '</td>');
                        html.push('<td><input type="text" error="总量" value="' + list.wTotal + '" /></td>');
                        if (list.wType == "检查") {
                            html.push('<td></td>');
                            html.push('<td></td>');
                        } else {
                            html.push('<td><input type="text" error="实用量" value="' + list.wReal + '" /></td>');
                            html.push('<td><input type="text" value="' + list.wUsage + '" /></td>');
                        }

                        html.push('<td style="display:none">' + list.wIsInjection + '</td>'); //
                        if (list.wType == "检查") {
                            html.push('<td>' + list.wBatch + '</td>');
                        } else {
                            html.push('<td><input type="text" error="批号" value="' + list.wBatch + '" /></td>');
                        }
                        html.push('<td>' + list.wValid + '</td>');
                        if (list.wType == "检查") {//库存数
                            html.push('<td></td>');
                        } else {
                            html.push('<td>' + list.iAmount + '</td>');
                        }
                        html.push('<td style="display:none">' + list.wPrice + '</td>');
                        html.push('<td style="display:none">' + list.wType + '</td>');
                        html.push('<td style="display:none">' + list.wCode + '</td></tr>');
                        realRow++;               
                        $("#wDiagnosis").val(list.wDiagnosis);
                        $("#wWeight").val(list.wWeight);
                    }
                }
                if (callTemplateData && callTemplateData.length > 0) {
                    callTemplateData = eval('(' + callTemplateData + ')');
                    for (var i in callTemplateData.Rows) {
                        var list = callTemplateData.Rows[i];
                        html.push('<tr><td></td>');
                        html.push('<td><input type="text" error="药品名称" title="可输入诊疗项目、条码、名称或简码" value="' + list.rName + '" /></td>');
                        html.push('<td>' + list.rSpec + '</td>');
                        html.push('<td>' + list.rUnit + '</td>');
                        html.push('<td><input type="text" error="总量" value="' + list.rTotal + '" /></td>');
                        html.push('<td><input type="text" error="实用量" value="' + list.rReal + '" /></td>');
                        html.push('<td><input type="text" value="' + list.rUsage + '" /></td>');
                        html.push('<td style="display:none">' + list.rIsInjection + '</td>');
                        html.push('<td><input type="text" error="批号" value="' + list.iBatch + '" /></td>');
                        html.push('<td>' + list.iValid + '</td>');
                        html.push('<td>' + list.iAmount + '</td>'); //库存数
                        html.push('<td style="display:none">' + list.iPrice + '</td>');
                        html.push('<td style="display:none">' + list.flag + '</td>');
                        html.push('<td style="display:none">' + list.iCode + '</td></tr>');

                        realRow++;
                    }
                }
                for (var i = realRow; i <= rowCount; i++) {
                    html.push(emptyRow);
                }
                $("#WesternGrid tbody").html(html.join(""));
                $("#WesternGrid tbody tr td").each(function() {
                    $(this).width(widths[$(this).index()]);
                });
                $("#cOther").empty();
                $("#cDrug").empty();
                var input = $('<input type="text" title="可输入诊疗项目、条码、名称或简码" />').appendTo($("#WesternGrid tbody tr:eq(" + (realRow - 1) + ") td:eq(1)"));

                bindAutocomplete($("#WesternGrid tbody tr").find("td:eq(1) input"));
                usageAutocomplete($("#WesternGrid tbody tr").find("td:eq(6) input"));
                //批号绑定提示
                WesternEvents();
                countTotal();
                $("#WesternGrid tbody tr").find("td:eq(8) input").each(function() {
                    var code = $(this).parent().parent().find("td:eq(13)").html();
                    batchAutocomplete($(this), code);
                });
                setTrNo();
                wNum = $("#wNum").val();
                if (type == "view") { //查看

                    changeButton(false);
                    $("input[type='text']").each(function() {
                        $(this).parent().prepend($(this).val());
                        $(this).remove();
                    });
                    $("select").each(function() {
                        $(this).parent().append($(this).find("option:selected").text());
                        $(this).remove();
                    });
                }
            }
            function setTrNo() {//生成序号
                for (var i = 0; i < rowCount; i++) {
                    //countTotal();
                    $("#WesternGrid tbody tr:eq(" + i + ") td:eq(0)").html((i + 1)).attr("title", i < realRow - 1 ? "点击删除该行数据" : "");
                }
            }
            function bindAutocomplete(jqueryObject) {
                jqueryObject.autocomplete("../../MCommon/QueryDrugAndTreat.ashx?action=getWestern", {
                    title: "barcode",
                    width: 400,
                    offsets: [-10, 0],
                    thead: [
                        { text: "类型", width: 50 },
                        { text: "药品名称/检查项目", width: 50 },
                        { text: "规格", width: 50 },
                        { text: "单位", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "flag,dName,dSpec,dUnit";
                    }
                }).result(function(e, row) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.data("data", row);
                    target.val(row.dName);
                    tr.find('td:eq(2)').html(row.dSpec);
                    tr.find('td:eq(3)').html(row.dUnit);

                    tr.find('td:eq(11)').html(row.iPrice);
                    tr.find('td:eq(12)').html(row.flag);
                    tr.find('td:eq(13)').html(row.iCode);
                    if (row.flag == "检查") {
                        tr.find('td:eq(4)').html('<input type="text" value="1" error="总量" />');
                        countTotal();
                    } else {//为药品的的时候才有用法
                        tr.find('td:eq(4)').html('<input type="text" error="总量" />');
                        var usageInput = $('<input type="text" />'),
                        batchInput = $('<input type="text" error="批号" />');
                        tr.find('td:eq(5)').html('<input type="text" error="实用量" />');
                        tr.find('td:eq(6)').append(usageInput);
                        tr.find('td:eq(8)').append(batchInput.val(row.iBatch));
                        tr.find('td:eq(9)').html(row.iValid);
                        tr.find('td:eq(10)').html(row.iAmount);

                        //countTotal();
                        usageAutocomplete(usageInput);
                        batchAutocomplete(batchInput, row.iCode);
                    }
                    addBlankRow(tr.index());
                    tr.find('td:eq(4) input').focus();
                    WesternEvents();
                }).removeRelation(function(e) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.data("data", "");
                    target.parent().nextAll().html("");
                });
            }
            function batchAutocomplete(jqueryObject, code) {
                jqueryObject.autocomplete("../../MCommon/QueryInventory.ashx?action=getBatch&code=" + code, {
                    title: "batch",
                    width: 400,
                    offsets: [-10, 0],
                    thead: [
                        { text: "批号", width: 50 },
                        { text: "有效期", width: 50 },
                        { text: "库存数", width: 50 },
                        { text: "可用库存数", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "iBatch,iValid,iAmount,iUsable";
                    },
                    formatMatch: function(row, i, max) {
                        return "iBatch";
                    }
                }).result(function(e, row) {
                    var target = $(e.target), tr = target.parent().parent(),
                    total = tr.find('td:eq(4) input').val() * 1;
                    target.val(row.iBatch);
                    if (row.iAmount * 1 < total) {
                        top.showTipsMsg('选择的[库存数]不能小于输入的[总量]!', 1, 3000);
                    } else {
                        tr.find('td:eq(9)').html(row.iValid);
                        tr.find('td:eq(10)').html(row.iUsable);
                    }
                }).removeRelation(function(e) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.find('td:eq(9)').html("");
                    tr.find('td:eq(10)').html("");
                });
            }
            function usageAutocomplete(jqueryObject) {
                jqueryObject.autocomplete("../../MCommon/QueryUsage.ashx?action=getUsage", {
                    title: "usage",
                    width: 400,
                    offsets: [-10, 0],
                    thead: [
                        { text: "用法", width: 50 },
                        { text: "是否注射", width: 50 },
                        { text: "类别", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "dUsage,dIsInjection,dCategory";
                    },
                    formatMatch: function(row, i, max) {
                        return "dUsage,dSimple";
                    }
                }).result(function(e, row) {
                    var target = $(e.target);
                    target.val(row.dUsage);
                    target.parent().next().html(row.dIsInjection);
                    //countTotal();
                }).removeRelation(function(e) {
                    $(e.target).parent().next().html("");
                });
            }
            function setIsInjection() {
                for (var i = realRow - 2; i >= 0; i--) {
                    var tr = $("#WesternGrid tbody").find("tr:eq(" + i + ")"),
                    IsInjection = "",
                    iUsage = tr.find("td:eq(6)").html();
                    if (iUsage.length > 0) { //有用法
                        IsInjection = tr.find("td:eq(7)").html();
                    } else {
                        if (tr.find("td:eq(7)").html().length == 0) {
                            tr.find("td:eq(7)").html("否");
                        }
                        continue;
                    }
                    for (var j = i - 1; j >= 0; j--) {
                        var row = $("#WesternGrid tbody").find("tr:eq(" + j + ")"),
                        jUsage = row.find("td:eq(6)").html();
                        if (jUsage.length > 0) {//有用法
                            break;
                        } else {
                            row.find("td:eq(7)").html(IsInjection);
                        }
                    }
                }
            }
            function medicalAutocomplete() {
                $("#wName").autocomplete("../../MCommon/QueryPatient.ashx?action=getInfo", {
                    title: "PatientInfo",
                    width: 700,
                    thead: [
                        { text: "姓名", width: 30 },
                        { text: "性别", width: 30 },
                        { text: "电话", width: 30 },
                        { text: "出生日期", width: 20 },
                        { text: "住址", width: 30 },
                        { text: "过敏史", width: 20 }
                    ],
                    formatItem: function(row, i, max) {
                        return "pName,Sex,pTelephone,pBirth,pAddress,pAllergy";
                    },
                    formatMatch: function(row, i, max) {
                        return "pName";
                    },
                    formatResult: function(row) {
                        return row.pName;
                    }
                }).result(function(e, row) {
                    $("#wName").val(row.pName);
                    $("#wSex").find("option[value='" + row.Sex + "']").attr("selected", true);
                    var age = row.age.split('-');
                    $("#wAge").val(age[0]);
                    $("#wAgeUnit").find("option[value='" + age[1] + "']").attr("selected", true);
                    $("#wAddress").val(row.pAddress);
                    $("#wAllergy").val(row.pAllergy);
                }).removeRelation(function(e) {
                    $("#wName").val("");
                    $("#wAge").val("");
                    $("#wAddress").val("");
                    $("#wAllergy").val("");
                });
            }
            function DiagnosisAutocomplete() {//临时诊断
                $("#wDiagnosis").autocomplete("../../MCommon/QueryDiagnosis.ashx?action=getDiagnosis", {
                    title: "Diagnosis",
                    thead: [
                        { text: "诊断结果", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "dDiagnosis";
                    },
                    formatMatch: function(row, i, max) {
                        return "dDiagnosis";
                    },
                    formatResult: function(row) {
                        return row.dDiagnosis;
                    }
                });
            }
            function observeAutocomplete() {
                $("#cObserve").autocomplete("../../MCommon/QueryTreat.ashx?action=getObserve", {
                    title: "observe",
                    width: 200,
                    thead: [
                        { text: "名称", width: 50 },
                        { text: "费用", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "tName,tPrice";
                    },
                    formatMatch: function(row, i, max) {
                        return "tName,tPrice";
                    },
                    formatResult: function(row) {
                        return row.tPrice;
                    }
                }).result(function(e, row) {
                    $("#cObserve").val(row.tPrice);
                    add();
                }).removeRelation(function(e) {
                    $("#cObserve").val("");
                    add();
                });
            }
            function bindEvents() {
                showDetail($("#WesternGrid tbody"));
                $("#btnAdd").click(function() {
                    top.art.dialog.reload("Western_Form", "/MBusiness/SysRecipe/WesternForm.aspx");
                });
                $("#btnUpdate").click(function() {
                    top.art.dialog.reload("Western_Form", "/MBusiness/SysRecipe/WesternForm.aspx?key=" + $("#wNum").val());
                });
                $("#WesternGrid 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--;
                                $("#WesternGrid tbody").append(emptyRow);

                                $("#cOther").empty();
                                $("#cDrug").empty();
                                setTrNo();
                                countTotal();
                            }
                        });
                    }
                });
                $("#btnPrint").click(function() {
                    $.get("WesternList.aspx", { action: "print", num: wNum }, function(data) {
                        printModule.print(data, false);
                    });
                });
                $("#btnClose").click(function() {
                    top.art.dialog.close('Western_Form');
                });
                $("#btnSave").click(function() {
                    save();
                });
                $("#btnCallTemplate").click(function() {
                    top.openDialog("/MBusiness/SysRecipeTemplate/RecipeTemplateList.aspx?type=call", "Recipe_Template", '处方模板- 调用', 1000, 530, 50, 50, callTemplateCallback);
                });
                $("#btnNewPatient").click(function() {
                    top.openDialog("/MBase/SysPatient/PatientForm.aspx?type=call", "Patient_Form", '患者信息- 添加', 700, 230, 50, 50, callPatientCallback);
                });
                $("#btnCallHistory").click(function() {
                    if (!$("#wName").val()) {
                        top.showTipsMsg('请先输入[姓名]!', 1, 3000);
                    } else {
                        top.art.dialog.data('wName', $("#wName").val() + dataSplit[0] + $("#wAddress").val()); // 存储数据
                        top.openDialog("/MBusiness/SysRecipe/WesternHistory.aspx", "Western_History", '历史处方-调用', 1000, 530, 50, 50, callHistoryCallback);
                    }
                });
            }
            function callTemplateCallback() {
                var currentID = top.art.dialog.data('TemplateValue'); // 读取处方模板选择的数据
                if (currentID) {
                    bindTemplate(currentID);
                }
            }
            function bindTemplate(currentID) {//调用处方模板
                var callTemplateData;
                $.ajax({
                    url: '../../MCommon/QueryRecipeTemplate.ashx',
                    data: { action: "callTemplate", parentID: currentID },
                    async: false,
                    success: function(rs) {
                        callTemplateData = rs;
                    }
                });
                loadData(callTemplateData);
            }
            function callPatientCallback() {
                var value = top.art.dialog.data('PatientValue'); // 读取新增患者的数据
                if (value) {
                    $.post(url, { action: "callPatient", value: value }, function(data) {
                        data = eval("(" + data + ")");
                        var list = data.Rows[0];
                        $("#wName").val(list.pName);
                        $("#wSex").val(list.pSex == '0' ? "男" : "女");
                        //年龄
                        var age = list.age.split('-');
                        $("#wAge").val(age[0]);
                        $("#wAgeUnit").find("option[value='" + age[1] + "']").attr("selected", true);
                        $("#wAddress").val(list.pAddress);
                        $("#wAllergy").val(list.pAllergy);
                    });
                }
            }
            function callHistoryCallback() {
                var code = top.art.dialog.data("recipeHistory");
                if (code) {
                    $.ajax({
                        url: url,
                        data: { action: 'query', key: code },
                        async: false,
                        success: function(rs) {
                            recipeData = rs;
                        }
                    });
                    loadData();
                }
            }
            init();
        })();
        function add() {
            var drug = 0, General = 0, Observe = 0, Material = 0, Other = 0, Receivable = 0;
            if ($.isNumeric($("#cDrug").val())) {
                drug += $("#cDrug").val() * 1;
                Receivable += drug;
            }
            if ($.isNumeric($('#cGeneral ').val())) {
                General += $("#cGeneral ").val() * 1;
                Receivable += General;
            }
            if ($.isNumeric($('#cObserve').val())) {
                Observe += $("#cObserve").val() * 1;
                Receivable += Observe;
            }

            if ($.isNumeric($('#cOther').val())) {
                Other += $('#cOther').val() * 1;
                Receivable += Other;
            }
            if ($.isNumeric($('#cMaterial').val())) {
                Material += $('#cMaterial').val() * 1;
                Receivable += Material;
            }
            $("#cReceivable").val(Receivable.toFixed(0));
            $("#cReal").val(Receivable.toFixed(0));
        }
    </script>
</body>
</html>
