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

<%@ Register Src="../../Controls/Condition.ascx" TagName="Condition" TagPrefix="ucCondition" %>
<%@ Register Src="../../Controls/QueryButton.ascx" TagName="QueryButton" TagPrefix="ucQueryButton" %>
<%@ Register Src="../../Controls/Pager.ascx" TagName="Pager" TagPrefix="ucPager" %>
<%@ Register Src="../../Controls/Grid.ascx" TagName="Grid" TagPrefix="ucGrid" %>
<!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="../../js/myLib/autoComplete.js" type="text/javascript"></script>
    <script src="../../js/myLib/helper.js" type="text/javascript"></script>
    <script src="../../js/myLib/Grid.js" type="text/javascript"></script>
    <style>
        .rpTree{font: 12px "微软雅黑","宋体"; width:100%; height:350px; border-top:1px solid #ccc;cursor:pointer; overflow-y:auto}
        .rpTree ul{ margin:0;list-style:none; padding:0}
        .rpTree li{ padding-left:10px; margin-top:2px}
    </style>
</head>
<body>
    <table id="table">
        <tr>
            <td style="width:200px">
                <div class="pt-panel" style="height:460px">
                    <strong>处方类别</strong>
                    <div class="pt-padding" style="text-align:center" >
                        <ucQueryButton:QueryButton ID="btnCategory" Text="新增类别" runat="server" />
                        <ucQueryButton:QueryButton ID="btnItem" Text="新增病症" runat="server" />
                    </div>
                    <div class="pt-padding" style="text-align:center" >
                        <ucQueryButton:QueryButton ID="btnEdit" Text="编辑" runat="server" />
                        <ucQueryButton:QueryButton ID="btnDelete" Text="删除" runat="server" />
                    </div>
                    <div id="Category" class="pt-tree">
                        <%=GetCategory() %>
                    </div>
                </div>
            </td>
            <td style="width:498px">
                <div class="pt-panel" style="margin-left:3px; height:460px">
                    <strong>处方模板</strong>
                    <div id="templatePanel" style="display:none">
                        <div class="pt-padding" >
                            <ucQueryButton:QueryButton ID="btnEditTemplate" Text="编辑" runat="server" />
                            <ucQueryButton:QueryButton ID="btnSave" Text="保存" runat="server" />
                            <ucQueryButton:QueryButton ID="btnClear" Text="删除" runat="server" />
                        </div>
                        <table id="templateGrid" class="pt-bill-grid">
                            <thead>
                                <tr>
                                    <td style="width: 40px">行号</td>
                                    <td style="width: 120px">药品名称</td>
                                    <td style="width: 70px">规格</td>
                                    <td style="width: 40px">单位</td>
                                    <td style="width: 40px">总量</td>
                                    <td style="width: 40px">实用量</td>
                                    <td style="width: 110px">用法</td>
                                    <td style="display:none">是否注射</td>
                                    <td style="width:13px"></td>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                        <div class="pt-line"></div>
                    </div>
                    <div id="nodataPanel" style="text-align:center; display:none">
                        <h2 style="color:#ccc; margin-top:200px">无处方模板信息</h2>
                        <input type="button" id="btnAddTemplate" class="pt-button active" value="创建处方模板" />
                    </div>
                    <div id="tipPanel" style="text-align:center">
                        <h2 style="color:#ccc; margin-top:200px">请选择具体的病症</h2>
                    </div>
                </div>
            </td>
            <td>
                <div class="pt-panel" style="margin-left:3px;height:460px">
                    <h1>Rp</h1>
                    <div class="rpTree">
                        <ul id="template"></ul>
                    </div>
                </div>
            </td>
        </tr>
    </table>
    <div class="pt-tip" style="display:none" id="callTip">友情提示：双击具体的病症可以调用对应的处方模板</div>
    <script>
        (function() {
            var dataSplit = 'Θ ☺ ☻'.split(' '),
            url = "RecipeTemplateList.aspx",
            categoryDialogUrl = "/MBusiness/SysRecipeTemplate/CategoryForm.aspx",
            categoryDialogFormName = "Category_Form",
            itemDialogUrl = "/MBusiness/SysRecipeTemplate/ItemForm.aspx",
            itemDialogFormName = "Item_Form",
            title = '<%=ModuleName %>',
            type = '<%=type %>',
            emptyRow = '<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td style="display:none"></td></tr>',
            widths = [],

            isExpand=false,//是否展开树
            currentLevel = -1,
            currentID = "",
            currentName = "",
            templateData = "",

            rowCount = 50,
            realRow = 1,

            tipPanel = $("#tipPanel"),
            templatePanel = $("#templatePanel"),
            nodataPanel = $("#nodataPanel");

            function init() {
                setTree();
                $("#templateGrid thead tr td").each(function() {
                    widths.push(getStyle($(this).attr("style"), "width"));
                });
                FixedTableHeader("templateGrid", 390);
                //bindTemplate();
                showTip();
                bindEvents();
                categoryEvents();
            }
            function setTree(){
                if(isExpand){
                    $("#Category").find("h4 img").attr("src","../../images/minus.gif");
                    $("#Category").find("ul").show();
                }else{
                    $("#Category").find("h4 img").attr("src","../../images/plus.gif");
                    $("#Category").find("ul").hide();
                }
            }

            function setPage() {
                var html = [];
                realRow = 1;
                if (templateData.length > 0) {
                    templateData = eval('(' + templateData + ')');
                    var description = templateData.Rows[0].rDescription.split(dataSplit[1]), templateContent = [];

                    for (var i = 0; i < description.length; i++) {
                        templateContent.push("<li>");
                        templateContent.push(description[i]);
                        templateContent.push("</li>");
                    }
                    $("#template").html(templateContent.join('').replace(/Θ/g, '&nbsp;&nbsp;&nbsp;'));

                    for (var i in templateData.Rows) {
                        var list = templateData.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></tr>');

                        realRow++;
                    }
                }
                for (var i = realRow; i <= rowCount; i++) {
                    html.push(emptyRow);
                }
                $("#templateGrid tbody").html(html.join(""));
                $("#templateGrid tbody tr td").each(function() {
                    $(this).width(widths[$(this).index()]);
                });

                $('<input type="text" error="药品名称" title="可输入条码、名称或简码" />').appendTo($("#templateGrid tbody tr:eq(" + (realRow - 1) + ") td:eq(1)"));

                bindAutocomplete($("#templateGrid tbody tr").find("td:eq(1) input"));
                usageAutocomplete($("#templateGrid tbody tr").find("td:eq(6) input"));
                setTrNo();
                templateEvents();
            }
            function setTrNo() {//生成序号
                for (var i = 0; i < rowCount; i++) {
                    $("#templateGrid tbody tr:eq(" + i + ") td:eq(0)").html((i + 1)).attr("title", i < realRow - 1 ? "点击删除该行数据" : "");
                }
            }
            function createRp() {
                var i = 1, isStart = true;

                var html = [];
                $("#templateGrid tbody").find("tr").each(function() {
                    var tds = $(this).find("td"), index = $(this).index(), liHtml = [];
                    if (index > 0 && index > realRow - 2) {
                        return false;
                    }
                    liHtml.push('<li>');
                    if (isStart) {
                        liHtml.push(i);
                        liHtml.push('.');
                    } else {
                        liHtml.push("&nbsp;&nbsp;&nbsp;");
                    }
                    liHtml.push(tds[1].firstChild.value); //药品名称
                    liHtml.push(tds[2].innerText); //规格
                    liHtml.push('*');
                    if (tds[4].firstChild) {
                        liHtml.push(tds[4].firstChild.value); //总量
                    }
                    liHtml.push(tds[3].innerText); //单位
                    if (!tds[6].firstChild || (tds[6].firstChild && tds[6].firstChild.value.indexOf("口服") == -1)) {
                        liHtml.push("&nbsp;&nbsp;&nbsp;");
                        if (tds[5].firstChild) {
                            liHtml.push(tds[5].firstChild.value); //实用量
                        }
                    }
                    liHtml.push('</li>');
                    isStart = false;

                    if (tds[6].firstChild && tds[6].firstChild.value.length != 0) {//用法不为空
                        liHtml.push("<li>");
                        liHtml.push("&nbsp;&nbsp;&nbsp;");
                        liHtml.push("用法：");
                        if (tds[6].firstChild.value.indexOf("口服") != -1) {
                            if (tds[5].firstChild) {
                                liHtml.push(tds[5].firstChild.value); //实用量
                            }
                            liHtml.push("&nbsp;&nbsp;&nbsp;");
                        }
                        liHtml.push(tds[6].firstChild.value);
                        liHtml.push("</li>");
                        i++;
                        isStart = true;
                    }
                    html.push(liHtml.join(''));

                });
                $("#template").html(html.join(''));
            }
            function templateEvents() {
                $('input[type="text"]').on("blur", function() {
                    createRp();
                });
            }
            function showTip() {
                tipPanel.show();
                nodataPanel.hide();
                templatePanel.hide();
            }
            function showNodata() {
                tipPanel.hide();
                nodataPanel.show();
                templatePanel.hide();
            }
            function showTemplate() {
                tipPanel.hide();
                nodataPanel.hide();
                templatePanel.show();
            }
            function bindTemplate(isLoad) {
                $("#template").html('');
                if (currentLevel != 1) return;
                $.ajax({
                    url: '../../MCommon/QueryRecipeTemplate.ashx',
                    data: { action: "query", parentID: currentID },
                    async: false,
                    success: function(rs) {
                        templateData = rs;
                    }
                });
                if (templateData.length == 0) {
                    showNodata();
                } else {
                    $("#btnEditTemplate").show();
                    $("#btnClear").show();
                    $("#btnSave").hide();
                    showTemplate();
                }
                setPage();
                if (isLoad) {
                    endEdit($("#templateGrid tbody"));
                    //                    loadRp();
                }
            }
            function addBlankRow(index) {
                if (index + 1 < rowCount) {
                    var td = $("#templateGrid 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();
                templateEvents();
            }
            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);
                    createRp();
                }).removeRelation(function(e) {
                    $(e.target).parent().nextAll().html("");
                });
            }
            function bindAutocomplete(jqueryObject) {
                jqueryObject.autocomplete("../../MCommon/QueryDrug.ashx?action=getDrug", {
                    title: "barcode",
                    width: 400,
                    offsets: [-10, 0],
                    thead: [
                        { text: "药品名称", width: 50 },
                        { text: "规格", width: 50 },
                        { text: "单位", width: 50 }
                    ],
                    formatItem: function(row, i, max) {
                        return "Name,Spec,Unit";
                    },
                    formatMatch: function(row, i, max) {
                        return "Code,Name,SimpleCode";
                    }
                }).result(function(e, row) {
                    var target = $(e.target), tr = target.parent().parent(),
                    usageInput = $('<input type="text" />');
                    tr.data("data", row);
                    target.val(row.Name);
                    tr.find('td:eq(2)').html(row.Spec);
                    tr.find('td:eq(3)').html(row.Unit);
                    tr.find('td:eq(4)').html('<input type="text" error="总量" />');
                    tr.find('td:eq(5)').html('<input type="text" error="实用量" />');
                    tr.find('td:eq(6)').append(usageInput);
                    usageAutocomplete(usageInput);
                    addBlankRow(tr.index());
                    createRp();
                }).removeRelation(function(e) {
                    var target = $(e.target), tr = target.parent().parent();
                    tr.data("data", "");
                    target.parent().nextAll().html("");
                });
            }
            
            
            
            function categoryEvents() {
//                $("#Category").click(function(e) {
//                    var target = $(e.target);
//                    if (target.is("div")) {
//                        if (target.parent().is("h4")) {
//                            currentLevel = 0;
//                            currentID = target.attr("data");
//                            currentName = target.html();
//                            removeHighlight();
//                            target.addClass("pt-highlight");
//                            showTip();
//                            $("#template").html('');
//                        } else {
//                            if (target.parent().parent().prev().is("h4")) {
//                                currentLevel = 1;
//                                currentID = target.attr("data");
//                                currentName = target.html();
//                                removeHighlight();
//                                target.addClass("pt-highlight");
//                                bindTemplate(true);
//                            }
//                        }
//                    }
//                });
                
                $("#Category").click(function(e) {
                    var target = $(e.target),
                    currentTarget=null,//触发的菜单
                    menuTarget=null;//子菜单
                    
                    if (target.is("div")) {
                        if (target.parent().is("h4")) {
                            currentLevel = 0;
                            currentTarget = target;
                            menuTarget = target.parent().next();
                        } else if (target.parent().parent().prev().is("h4")) {
                            currentLevel = 1;
                            currentTarget=target;
                        }
                    }
                    if(target.is("img") || (target.is("span") && target.parent().parent().is("h4"))){
                        currentLevel = 0;
                        currentTarget = target.parent();
                        menuTarget = target.parent().parent().next();
                    }
                    if(target.is("span")&&target.parent().parent().parent().prev().is("h4")){
                        currentLevel = 1;
                        currentTarget = target.parent();
                    }
                    if(currentTarget!=null){
                        currentID = currentTarget.attr("data");
                        currentName = currentTarget.find("span").text();
                        removeHighlight();
                        currentTarget.addClass("pt-highlight");
                        if( currentLevel == 0 ){
                            showTip();
                            $("#template").html('');
                        
                            if(currentTarget.find("img").attr("src").indexOf("minus")!=-1){//展开的
                                if(menuTarget.is("ul")){
                                    menuTarget.hide();
                                }
                               
                                currentTarget.find("img").attr("src","../../images/plus.gif");
                            }else{
                                if(menuTarget.is("ul")){//如果没有子菜单，则menuTarget找到的将是相邻的DIV
                                    menuTarget.show();
                                }
                                currentTarget.find("img").attr("src","../../images/minus.gif");
                            }
                        }else if(currentLevel==1){
                            bindTemplate(true);
                        }
                    }
                });

                if (type !== "") {//西药处方调用处方模板
                    top.art.dialog.data('TemplateValue', ""); // 清空数据
                    $("#callTip").show(); //提示信息
                    $("#Category").dblclick(function(e) {
                        var target = $(e.target),currentTarget=null;
                        if(target.is("div") && target.parent().parent().prev().is("h4")){
                            currentTarget=target;
                        }
                        if(target.is("span") && target.parent().parent().parent().prev().is("h4")){
                            currentTarget=target.parent();
                        }
                        if(currentTarget!=null){
                            currentID = currentTarget.attr("data");
                            if (nodataPanel.is(":visible")) {
                                top.showTipsMsg('没有要调用的处方模板信息!', 1, 5000);
                            } else {
                                top.art.dialog.data('TemplateValue', currentID); // 存储数据
                                top.art.dialog.close('Recipe_Template');
                            }
                        }
                        
//                        if (target.is("div")) {
//                            if (target.parent().parent().prev().is("h4")) {
//                                currentID = target.attr("data");
//                                if (nodataPanel.is(":visible")) {
//                                    top.showTipsMsg('没有要调用的处方模板信息!', 1, 5000);
//                                } else {
//                                    top.art.dialog.data('TemplateValue', currentID); // 存储数据
//                                    top.art.dialog.close('Recipe_Template');
//                                }
//                            }
//                        }
                    });
                }
                $("#btnCategory").click(function() {
                    top.openDialog(categoryDialogUrl, categoryDialogFormName, '类别 - 添加', 700, 100, 50, 50);
                });
                $("#btnItem").click(function() {
                    if ($("#Category").children().length == 0) {
                        top.showTipsMsg('请先添加类别!', 1, 5000);
                        return;
                    }
                    top.openDialog(itemDialogUrl, itemDialogFormName, '病症 - 添加', 700, 100, 50, 50);
                });
                $("#btnEdit").click(function() {
                    if (currentLevel == -1) {
                        top.showTipsMsg('请选择要修改的病症!', 1, 5000);
                        return;
                    }
                    switch (currentLevel) {
                        case 0:
                            top.openDialog(categoryDialogUrl + "?key=" + currentID, categoryDialogFormName, '类别 - 编辑', 700, 100, 50, 50);
                            break;
                        case 1:
                            top.openDialog(itemDialogUrl + "?key=" + currentID, itemDialogFormName, '病症 - 编辑', 700, 100, 50, 50);
                            break;
                    }
                });
                $("#btnDelete").click(function() {
                    if (currentLevel == -1) {
                        top.showTipsMsg('请选择要删除的病症!', 1, 5000);
                        return;
                    }
                    top.showConfirmMsg("要删除名称为[" + currentName + "]的处方类别信息吗?", function(r) {
                        if (r) {
                            $.get(url, { action: "removeCategory", id: currentID }, function(data) {
                                if (data == "200") {
                                    top.showTipsMsg('删除成功!', 0, 5000);
                                    location.reload();
                                } else if (data == "100") {
                                    top.showTipsMsg('操作失败:您要删除的处方类别信息存在子项目!', 1, 5000);
                                } else {
                                    top.showTipsMsg('删除失败!', 1, 5000);
                                }
                            });
                        }
                    });
                });
            }
            function removeHighlight() {
                $(".pt-highlight").removeClass("pt-highlight");
            }
            function getDetails() {
                //单元格、行、表
                var data = [];
                $("#templateGrid 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); //是否注射
                        data.push(row.join(dataSplit[0]));
                    } else {
                        return false;
                    }
                });
                return data.join(dataSplit[1]);
            }
            function validateDetails() {
                //验证是否重复
                var isValidate = true;
                //验证是否有值
                $("#templateGrid 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 save() {
                if (!validateDetails()) return;
                endEdit($("#templateGrid tbody"));
                var result = false,
                description = $("#template").html().replace(/<li>/ig, '').replace(/<\/li>/ig, dataSplit[1]).replace(/&nbsp;&nbsp;&nbsp;/g, dataSplit[0]);
                $.ajax({
                    url: url,
                    type: "POST",
                    data: { action: "save", description: description, details: getDetails(), key: currentID },
                    async: false,
                    success: function(data) {
                        result = parseInt(data, 10) > 0;
                    },
                    error: function(ex) {
                        alert(ex);
                    }
                });
                if (result) {
                    top.showTipsMsg('保存成功!', 0, 3000);
                    $("#btnEditTemplate").show();
                    $("#btnClear").show();
                    $("#btnSave").hide();
                } else {
                    top.showTipsMsg("保存失败，请稍后重试", 1, 4000);
                }
            }
            function bindEvents() {
                $("#btnAddTemplate").click(function() {
                    if (currentLevel != 1) {
                        top.showTipsMsg('请选择[处方类别]最底层节点!', 1, 5000);
                        return;
                    }
                    $("#btnSave").show();
                    //编辑和删除按钮是禁用的
                    $("#btnEditTemplate").hide();
                    $("#btnClear").hide();
                    templateData = "";
                    setPage();
                    showTemplate();
                });
                $("#btnSave").click(function() {
                    save();
                });
                $("#btnClear").click(function() {
                    removeTemplate();
                });
                $("#btnEditTemplate").click(function() {
                    bindTemplate(false);
                    $("#btnSave").show();
                    $("#btnClear").hide();
                    $("#btnEditTemplate").hide();
                });
                $("#templateGrid 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--;
                                $("#templateGrid tbody").append(emptyRow);
                                setTrNo();
                                createRp();
                            }
                        });
                    }
                });
            }
            function removeTemplate() {
                top.showConfirmMsg("要删除病症为[" + currentName + "]的处方模板信息吗?", function(r) {
                    if (r) {
                        $.get(url, { action: "removeTemplate", id: currentID }, function(data) {
                            if (parseInt(data, 10) > 0) {
                                top.showTipsMsg('删除成功!', 0, 5000);
                                showNodata();
                            } else {
                                top.showTipsMsg('删除失败!', 1, 5000);
                            }
                        });
                    }
                });
            }
            init();
        })();
    </script>
</body>
</html>
