<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('处方登记信息')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: jasny-bootstrap-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <th:block th:include="include :: layout-latest-css" />
</head>
<body class="gray-bg">

    <div class="col-sm-12 search-collapse">
    <form id="dtp-form-hxcx" class="customize-search-form">
            <div class="customize-form-group-container">
                <div class="customize-form-group">
                    <label>患者信息:</label>
                    <input type="text" class="styled-input" placeholder="输入姓名,患者ID或手机号/证件号码" id="query" name="query"/>
                </div>
                <div class="customize-form-group">
                    <a class="btn btn-primary btn-rounded btn-sm" onclick="search_hz()">&nbsp;搜索</a>
                    <a class="btn btn-warning btn-rounded btn-sm" onclick="resetPre()">重置</a>
                    <a class="btn btn-info btn-rounded btn-sm" onclick="bookbuilding()">&nbsp快速建档</a>
<!--        bookbuilding  $.operate.addSetwht('快速建档','dtp/pmService/archivesAdd',800,750)-->
                </div>
            </div>
     </form>

        <div id="patient-table-container">
            <table id="patient-table" class="customize-table">
                <thead>
                <tr>
                    <th></th> <!-- 选择框 -->
                    <th>患者ID</th>
                    <th>患者姓名</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>证件类型</th>
                    <th>证件号码</th>
                    <th>临床诊断</th>
                    <th>联系电话</th>
                    <!-- 添加其他需要显示的列 -->
                </tr>
                </thead>
                <tbody>
                <!-- 数据行将由 JavaScript 动态插入 -->
                </tbody>
            </table>
        </div>
    </div>
    <div class="col-sm-12 search-collapse">
    <h4 class="query-condition-title">处方登记</h4>
    <form id="dtp-form-newcfxx" class="customize-search-form">
                    <div class="customize-form-group-container">
                        <div class="customize-form-group">
                            <label class="is-required">医院:</label>
<!--                            <input name="hospital" placeholder="医院" id="hospital" class="styled-input" type="text">-->
                            <select id="hospital-select"  name="hospital" class="styled-input form-control select2-multiple" placeholder="请选择或输入搜索">
                                <option value="">请选择医院</option>
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="is-required">处方医生:</label>
                            <input name="prescribingDoctor" id="prescribingDoctor" placeholder="处方医生"   class="styled-input" type="text">
                        </div>
                        <div class="customize-form-group">
                            <label>科室:</label>
                            <input name="department" id="department" placeholder="科室"   class="styled-input" type="text">
                        </div>
                        <div class="customize-form-group">
                            <label class="is-required">处方诊断:</label>
                            <input name="prescriptionDiagnosis" id="prescriptionDiagnosis" placeholder="处方诊断"   class="styled-input" type="text">
                        </div>
                        <div class="customize-form-group">
                            <label>主管医生:</label>
                            <input name="attendingDoctor" id="attendingDoctor" placeholder="主管医生"   class="styled-input" type="text">
                        </div>
                        <div class="customize-form-group-container">
                        </div>
<!--                        <div class="customize-form-group">-->
<!--                            <label class="is-required">临床诊断:</label>-->
<!--                            <input name="clinicalDiagnosis" id="clinicalDiagnosis" placeholder="临床诊断"   class="styled-input" type="text">-->
<!--                        </div>-->
                        <!--<div class="customize-form-group">
                            <label>处方图片:</label>
                            <input name="prescriptionImageUrl" id="prescriptionImageUrl" placeholder="处方图片"  class="styled-input" type="text">
                        </div>-->
                        <div class="customize-form-group  select-time">
                            <label class="is-required">处方开具日期:</label>
                            <input name="prescriptionIssueDate" id="prescriptionIssueDate" placeholder="处方开具日期"   class="time-input time-input2" type="text">
                        </div>
                        <div class="customize-form-group">
                            <label>发票编码:</label>
                            <input name="invoiceCode" id="invoiceCode" placeholder="发票编码"  class="styled-input" type="text">
                        </div>
                        <!--<div class="customize-form-group">
                            <label>发票图片:</label>
                            <input name="invoiceImageUrl" id="invoiceImageUrl" placeholder="发票图片"  class="styled-input" type="text">
                        </div>-->


<!--                        <div class="customize-form-group">-->
<!--                            <label class="is-required">登记药师姓名:</label>-->
<!--                            <input name="registerPharmacistName" id="registerPharmacistName" placeholder="登记药师姓名"   class="styled-input" type="text">-->
<!--                        </div>-->
                        <div class="customize-form-group">
                            <label>登记人:</label>
                            <input name="registrant" id="registrant" placeholder="未填登记人，系统默认当前用户"  class="styled-input" type="text">
                        </div>
                        <!--<div class="customize-form-group">
                            <label>审核药师姓名:</label>
                            <input name="reviewingName" id="reviewingName" placeholder="审核药师姓名"   class="styled-input" type="text">
                        </div>-->
                        <div class="customize-form-group">
                            <label>处方类型</label>
                            <select name="prescriptionType"  th:with="type=${@dict.getType('sys_select_prescription_ype')}" class="styled-input">
                                <option value="">全部</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                                ></option>
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">临床诊断：</label>
                            <select id="category-select"   class="styled-input form-control select2-multiple" multiple placeholder="请选择或输入搜索">

                            </select>
                        </div>

                    </div>
        <div class="customize-form-group-container">
            <div class="customize-form-group">
                <label>处方图片:</label>
                <div class="form-group">
                    <div class="fileinput fileinput-new" data-provides="fileinput">
                        <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;">
                            <img id="prescriptionImageUrl" th:if="${prescriptionImageUrl}" th:src="@{${prescriptionImageUrl}}" class="preview-image" />

                            <div th:unless="${prescriptionImageUrl}" class="centered-content">
                                <span class="plus-sign">+</span>
                            </div>
                        </div>
                        <div>
                            <input id="prescriptionImageUpload" name="prescriptionImageUpload" type="file">
                            <a href="javascript:;" class="btn btn-white" data-dismiss="fileinput">清除图片</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="customize-form-group">
                <label>发票图片:</label>
                <div class="form-group">
                    <div class="fileinput fileinput-new" data-provides="fileinput">
                        <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;">
                            <img id="invoiceImageUrl" th:if="${invoiceImageUrl}" th:src="@{${invoiceImageUrl}}" class="preview-image" />

                            <div th:unless="${invoiceImageUrl}" class="centered-content">
                                <span class="plus-sign">+</span>
                            </div>
                        </div>
                        <div>
                            <input id="invoiceImageUpload" name="invoiceImageUpload" type="file">
                            <a href="javascript:;" class="btn btn-white" data-dismiss="fileinput">清除图片</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
     </form>
        <!-- 假设这是你的 HTML 结构class="table table-bordered" -->
        <div class="ibox" id="data-ibox" style="overflow: auto;">
            <div class="ibox-title" style="width: 100%;">药品登记列表</div>
            <table class="fixed-layout-table table1" id="drugInfoTable">
                <thead>
                <tr>
                    <th>操作+<a type="button" class="btn btn-primary btn-sm" onclick="selectUsersToParentCallBack2()">添加药品</a></th>
                    <th>药品编码</th>
                    <th>药品名</th>
                    <th class="hidden-column">通用名</th>
                    <th>规格</th>
                    <th class="hidden-column">厂家简称</th>
                    <th class="hidden-column">给药方式</th>
                    <th class="hidden-column">是否随访管理品</th>
                    <th class="hidden-column">是否冷链管理品</th>
                    <th class="hidden-column">是否登记管理品</th>
                    <th class="hidden-column">是否慈善援助管理品</th>
                    <th class="hidden-column">包装</th>
                    <th class="is-required">取药数量(购药数量)</th>
                    <th class="is-required">单次剂量数</th>
                    <th class="is-required">单次剂量单位</th>
                    <th class="is-required">用药频次</th>
                    <th class="is-required">购药包装单位</th>
                    <th>D值品用药天数</th>

                </tr>
                </thead>
                <tbody>
                <!-- 数据行将被插入到这里 -->
                </tbody>
            </table>
        </div>
            <div class="center-block ibox-title" style="width: 100%;">
                <label class="is-required">是否开启药师审核：</label>
                    <button type="button" class="btn btn-primary"  onclick="onclickshow()">是</button>
                    <button type="button" class="btn btn-info"     onclick="onclickhide()">否</button>
            </div>
    </div>
    <div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <form class="form-horizontal" id="form-budan-add">
                <div class="modal-content animated bounceInRight">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">关闭</span></button>
                        <h2 class="modal-title">药师审核</h2>
                    </div>
                    <div class="modal-body">
                        <div class="customize-search-form">
                            <div class="customize-form-group">
                                <label>审核药师姓名:</label>
                                <select id="pharmacistNameSelect" name="pharmacistName" class="styled-input" style="width: 200px; height: 35px;">
                                    <option value="" disabled selected>请选择</option>
                                </select>
                                <span id="pharmacistVerified" class="verified-symbol" style="display:none;">✓</span>
                            </div>
                            <div id="passwordGroup" class="customize-form-group" style="display:none;">
                                <label>密码:</label>
                                <input type="password" placeholder="请输入密码" class="styled-input" style="width: 200px; height: 35px;" id="password" name="password">
                                <button type="button" class="btn btn-success btn-sm" id="verifyPasswordBtn">确定</button>
                            </div>
                            <div id="checkView" style="display:none;">
                                <div class="customize-form-group">
                                    <label>审核结果:</label>
                                    <div>
                                        <label><input type="radio" name="checkResult" value="1"> 通过</label>
                                        <label><input type="radio" name="checkResult" value="0"> 不通过</label>
                                    </div>
                                </div>
                                <div class="customize-form-group">
                                    <label>审核意见:</label>
                                    <input type="text" placeholder="请输入说明" class="styled-input" style="width: 200px; height: 35px;" id="remarks" name="remarks">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="submitReview()">提交</button>


                    </div>
                </div>
            </form>

        </div>

    </div>

    <div class="main-content">
        <div class="col-sm-offset-5 col-sm-10">

            <button type="button" class="btn btn-sm btn-info" onclick="openCheckYSSH()" id="openCheckYSSid">药师审核</button>&nbsp;

            <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>提 交</button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
    <th:block th:include="include :: jasny-bootstrap-js" />
<!--<th:block th:include="include :: bootstrap-fileinput-js" />-->
<th:block th:include="include :: bootstrap-table-fixed-columns-js" />
<th:block th:include="include :: layout-latest-js" />
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('dtp:RecipeRegister:edit')}]];
    var removeFlag = [[${@permission.hasPermi('dtp:RecipeRegister:remove')}]];
    var prefix_recipe = ctx + "dtp/recipe";
    var prefix_yppz= ctx + "yppz/drugConfig";
    var prefix_configInfo= ctx + "dtp/configInfo";

    var prefix_pmService = ctx + "dtp/pmService";
    var hzparam =[];
    var hzparam1 ={};
    var openId='';

    var remarks;
    var reviewingName;
    var reviewStatus;
    var data;
    var shangci=false;
    var shangcigyList=[];
    var dataList=[];
    var selectdataList=[];
    var  prescriptionNumber;
    var  drugsLinkId;
    var reviewFlag=true;
    var reviewFormData = new FormData();

    document.addEventListener('DOMContentLoaded', function () {
        // 初始化所有 .fileinput 区域
        document.querySelectorAll('.fileinput').forEach(function (fileInputWrapper) {
            initializeImagePreview2(fileInputWrapper);
        });
    });

    function initializeImagePreview2(fileInputWrapper) {
        var fileInput = fileInputWrapper.querySelector('input[type="file"]');
        var previewThumbnail = fileInputWrapper.querySelector('.fileinput-preview.thumbnail');
        var largePreview;
        var clearButton = fileInputWrapper.querySelector('.btn-white[data-dismiss="fileinput"]');

        // 创建大图预览
        function createLargePreview(imageSrc) {
            if (largePreview) {
                largePreview.style.display = 'none';
                largePreview.remove();
            }
            largePreview = document.createElement('div');
            largePreview.className = 'preview-large';
            largePreview.style.backgroundImage = 'url(' + imageSrc + ')';
            largePreview.style.width = '1000px'; // 根据需要调整宽度
            largePreview.style.height = '900px'; // 根据需要调整高度
            largePreview.style.backgroundSize = 'contain';
            largePreview.style.backgroundRepeat = 'no-repeat';
            largePreview.style.backgroundPosition = 'center';
            largePreview.style.position = 'absolute';
            largePreview.style.zIndex = '1000';
            largePreview.style.display = 'none'; // 初始状态下不显示

            // 添加到DOM
            fileInputWrapper.appendChild(largePreview);

            // 为大图预览添加事件监听器
            largePreview.onmouseover = function () {
                this.style.display = 'block';
            };

            largePreview.onmousemove = function (e) {
                updateLargePreviewPosition(e, previewThumbnail);
            };

            largePreview.onmouseout = function (e) {
                if (!previewThumbnail.contains(e.relatedTarget)) {
                    hideLargePreview();
                }
            };
        }

        // 悬停时显示大图
        function handleMouseOver(e) {
            /*if (previewThumbnail.style.backgroundImage && !largePreview) {
                createLargePreview(previewThumbnail.style.backgroundImage.replace(/^url$["']?/, '').replace(/["']?$$/, ''));
            }*/
            if (largePreview) {
                showLargePreview(e);
            }
        }

        // 鼠标移动时更新大图位置
        function handleMouseMove(e) {
            if (largePreview) {
                updateLargePreviewPosition(e, previewThumbnail);
            }
        }

        // 缩略图移出事件处理
        function handleMouseOut(e) {
            if (!largePreview || !largePreview.contains(e.relatedTarget)) {
                hideLargePreview();
            }
        }

        // 显示大图预览
        function showLargePreview(e) {
            largePreview.style.display = 'block';
            updateLargePreviewPosition(e, previewThumbnail);
        }

        // 更新大图预览位置
        function updateLargePreviewPosition(e, referenceElement) {
            const rect = referenceElement.getBoundingClientRect();
            const winWidth = window.innerWidth;
            const winHeight = window.innerHeight;
            const largePreviewWidth = largePreview.offsetWidth;
            const largePreviewHeight = largePreview.offsetHeight;

            let left = e.pageX ; // 尝试放置在鼠标右侧
            let top = e.pageY + 150; // 尝试放置在鼠标下方

            // 确保大图预览不超出浏览器窗口边界
            //if (left + largePreviewWidth > winWidth) left = e.pageX - largePreviewWidth - 150; // 如果右侧空间不足，则放在左侧
            if (top + largePreviewHeight > winHeight) top = e.pageY - largePreviewHeight; // 如果底部空间不足，则放在上方

            largePreview.style.left = left+100 + 'px';
            largePreview.style.top = top+300 + 'px';;
        }

        // 隐藏大图预览
        function hideLargePreview() {
            if (largePreview) {
                largePreview.style.display = 'none';
            }
        }

        // 移除图片和大图预览
        function removeImageAndPreview() {
            previewThumbnail.style.backgroundImage = ''; // 清空缩略图背景图片
            if (largePreview) {
                largePreview.style.display = 'none';
                largePreview.remove(); // 从 DOM 中移除 largePreview
                largePreview = null;
            }
            updateClearButtonVisibility(); // 更新清除按钮的可见性
        }

        // 更新清除按钮的可见性
        function updateClearButtonVisibility() {
            /*if (clearButton) {
                clearButton.style.display = previewThumbnail.style.backgroundImage ? 'inline-block' : 'none';
            }*/
        }

        // 监听文件上传变化事件
        fileInput.addEventListener('change', function (e) {
            // 清除现有的大图预览
            removeImageAndPreview();

            // 读取新文件并更新缩略图背景图片
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function (event) {
                    previewThumbnail.style.backgroundImage = 'url(' + event.target.result + ')';
                    // 立即创建大图预览以反映新图片
                    createLargePreview(event.target.result);
                    setupEventListeners(); // 重新设置事件监听器
                    updateClearButtonVisibility(); // 更新清除按钮的可见性
                };
                reader.readAsDataURL(this.files[0]);
            } else {
                updateClearButtonVisibility(); // 更新清除按钮的可见性
            }
        });

        // 初始化事件监听器
        function setupEventListeners() {
            previewThumbnail.onmouseover = handleMouseOver;
            previewThumbnail.onmousemove = handleMouseMove;
            previewThumbnail.onmouseout = handleMouseOut;

            // 监听清除按钮点击事件
            if (clearButton) {
                clearButton.addEventListener('click', function () {
                    removeImageAndPreview(); // 清除图片及大图预览
                });
            }
        }

        // 对于回显的图片，确保初始化时创建大图预览并更新清除按钮的可见性
        if (previewThumbnail.style.backgroundImage) {
            createLargePreview(previewThumbnail.style.backgroundImage.replace(/^url$["']?/, '').replace(/["']?$$/, ''));
            updateClearButtonVisibility();
        } else {
            updateClearButtonVisibility();
        }

        // 初始化事件监听器
        setupEventListeners();
    }
    document.addEventListener('DOMContentLoaded', function () {
        // 初始化所有 .fileinput 区域
        document.querySelectorAll('.fileinput').forEach(function (fileInputWrapper) {
            initializeImagePreview(fileInputWrapper);
        });
    });

    function initializeImagePreview(fileInputWrapper) {
        var previewThumbnail = fileInputWrapper.querySelector('.fileinput-preview.thumbnail');
        var imgElement = previewThumbnail.querySelector('.preview-image');
        var largePreview;
        var clearButton = fileInputWrapper.querySelector('.btn-white[data-dismiss="fileinput"]');

        if (!imgElement || !clearButton) return; // 如果没有img元素或清除按钮，则不执行后续操作

        // 创建大图预览
        function createLargePreview(img) {
            if (largePreview) {
                largePreview.style.display = 'none';
                largePreview.remove();
            }
            largePreview = document.createElement('div');
            largePreview.className = 'preview-large';
            largePreview.style.backgroundImage = 'url(' + img.src + ')';
            largePreview.style.width = '1000px'; // 根据需要调整宽度
            largePreview.style.height = '900px'; // 根据需要调整高度
            largePreview.style.backgroundSize = 'contain';
            largePreview.style.backgroundRepeat = 'no-repeat';
            largePreview.style.backgroundPosition = 'center';
            largePreview.style.position = 'absolute';
            largePreview.style.zIndex = '1000';
            largePreview.style.display = 'none'; // 初始状态下不显示

            // 添加到DOM
            fileInputWrapper.appendChild(largePreview);
        }

        // 悬停时显示大图
        function handleMouseOver(e) {
            if (imgElement.src && !largePreview) {
                createLargePreview(imgElement);
            }
            if (largePreview) {
                showLargePreview(e);
            }
        }

        // 鼠标移动时更新大图位置
        function handleMouseMove(e) {
            if (largePreview) {
                updateLargePreviewPosition(e, previewThumbnail);
            }
        }

        // 缩略图移出事件处理
        function handleMouseOut(e) {
            if (!largePreview || !largePreview.contains(e.relatedTarget)) {
                hideLargePreview();
            }
        }

        // 显示大图预览
        function showLargePreview(e) {
            largePreview.style.display = 'block';
            updateLargePreviewPosition(e, previewThumbnail);
        }

        // 更新大图预览位置
        function updateLargePreviewPosition(e, referenceElement) {
            const rect = referenceElement.getBoundingClientRect();
            const winWidth = window.innerWidth;
            const winHeight = window.innerHeight;
            const largePreviewWidth = largePreview.offsetWidth;
            const largePreviewHeight = largePreview.offsetHeight;

            let left = e.pageX + 150; // 尝试放置在鼠标右侧
            let top = e.pageY + 150; // 尝试放置在鼠标下方

            // 确保大图预览不超出浏览器窗口边界
            //if (left + largePreviewWidth > winWidth) left = e.pageX - largePreviewWidth - 150; // 如果右侧空间不足，则放在左侧
            if (top + largePreviewHeight > winHeight) top = e.pageY - largePreviewHeight; // 如果底部空间不足，则放在上方

            largePreview.style.left = left+100 + 'px';
            largePreview.style.top = top+400 + 'px'; // 保持原有的偏移量
        }

        // 隐藏大图预览
        function hideLargePreview() {
            if (largePreview) {
                largePreview.style.display = 'none';
            }
        }

        // 初始化事件监听器
        function setupEventListeners() {
            previewThumbnail.onmouseover = handleMouseOver;
            previewThumbnail.onmousemove = handleMouseMove;
            previewThumbnail.onmouseout = handleMouseOut;

            // 监听清除按钮点击事件
            clearButton.addEventListener('click', function () {
                removeImageAndPreview(); // 清除图片及大图预览
            });
        }

        // 移除事件监听器
        function removeEventListeners() {
            previewThumbnail.onmouseover = null;
            previewThumbnail.onmousemove = null;
            previewThumbnail.onmouseout = null;
        }

        // 监听文件上传变化事件
        function setupFileInputChange(uploadId) {
            let upload = fileInputWrapper.querySelector(`#${uploadId}`);
            if (upload) {
                upload.addEventListener('change', function (e) {
                    // 清除现有的大图预览
                    removeImageAndPreview();

                    // 读取新文件并更新 <img> 元素的 src 属性
                    if (this.files && this.files[0]) {
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            imgElement.src = event.target.result;
                            // 立即创建大图预览以反映新图片
                            createLargePreview(imgElement);
                            setupEventListeners(); // 重新设置事件监听器
                            updateClearButtonVisibility(); // 更新清除按钮的可见性
                        };
                        reader.readAsDataURL(this.files[0]);
                    } else {
                        imgElement.src = ''; // 清空图片源
                        removeEventListeners(); // 移除事件监听器
                        updateClearButtonVisibility(); // 更新清除按钮的可见性
                    }
                });
            }
        }

        // 移除图片和大图预览并更新清除按钮的可见性
        function removeImageAndPreview() {
            imgElement.src = ''; // 清空图片源
            if (largePreview) {
                largePreview.style.display = 'none';
                largePreview.remove(); // 从 DOM 中移除 largePreview
                largePreview = null;
            }
            removeEventListeners(); // 移除事件监听器
            updateClearButtonVisibility(); // 更新清除按钮的可见性
        }

        // 更新清除按钮的可见性
        function updateClearButtonVisibility() {
            if (clearButton && imgElement) {
                clearButton.style.display = imgElement.src !== '' ? 'inline-block' : 'none';
            }
        }

        // 初始化
        setupEventListeners();

        // 对应的文件上传控件ID
        let fileId = fileInputWrapper.querySelector('input[type="file"]')?.id;
        if (fileId) {
            setupFileInputChange(fileId);
        }

        // 对于回显的图片，确保初始化时创建大图预览并更新清除按钮的可见性
        if (imgElement.src) {
            createLargePreview(imgElement);
            updateClearButtonVisibility();
        } else {
            updateClearButtonVisibility();
        }
    }

     $(document).ready(function() {
        // 获取所有的输入元素（input, textarea, select）
        var $inputs = $('form').find('input, textarea, select').filter(':visible');

        $inputs.each(function(index) {
            $(this).on('keydown', function(e) {
                if (e.key === "Enter" || e.keyCode === 13) {
                    e.preventDefault(); // 阻止默认行为（例如提交表单）

                    // 找到当前输入框的索引
                    var currentIndex = $inputs.index(this);

                    // 如果不是最后一个输入框，则聚焦下一个输入框
                    if (currentIndex < $inputs.length - 1) {
                        $inputs.eq(currentIndex + 1).focus();
                    } else {
                        // 如果是最后一个输入框，可以选择提交表单或不做任何事情
                        // $(this).closest('form').submit();
                    }
                }
            });
        });

        // 监听选择变化
        $(document).on('change', 'input[name="selectPatient"]', function() {
            // 移除所有行的 'selected' 类
            $('#patient-table tbody tr').removeClass('selected');

            // 获取当前选中的行并添加 'selected' 类
            var selectedRow = $(this).closest('tr');
            selectedRow.addClass('selected');

            // 获取选中的患者对象
            var selectedPatient = getSelectedPatient();
            if (selectedPatient) {
                // 调用 getLastRecipe 方法，传入患者的 ID
                var patientId = selectedPatient.id;
                getLastRecipe(patientId);
            }
        });
         // 初始化 Select2 插件
         $('#hospital-select').select2({
             placeholder: "请选择或直接输入搜索",
             //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
         });
         // Listen for the 'select2:select' event
         $('#hospital-select').on('select2:select', function(e) {
             var clearSpan = $('.select2-selection-clear');
             if (clearSpan.length > 0) {
                 clearSpan.remove();
             }
         });
         // 发送 AJAX 请求获取疾病大类数据
         $.ajax({
             url: prefix_configInfo+'/dtpHospitalList',
             method: 'POST',
             dataType: 'json',
             success: function(data) {
                 var options = $('#hospital-select');
                 // 清空已有选项（除了第一个默认选项）
                 options.find('option').not(':first').remove();
                 $('<option>', {
                     value: '',
                     text : '请选择疾病医院'
                 }).appendTo(options);
                 // 遍历返回的数据并添加选项
                 $.each(data.value, function(index, item) {
                     $('<option>', {
                         value: item.id,
                         text : item.standardName
                     }).appendTo(options);
                 });

                 // 重新初始化 Select2 以反映新的选项
                 options.trigger('change');
             },
             error: function(xhr, status, error) {
                 $.modal.alertError("解析疾病失败");
             }
         });

         // 初始化 Select2
         $('#category-select').select2({
             placeholder: '--输入疾病名称搜索--',
             allowClear: true,
             ajax: {
                 url: prefix_recipe+'/searchICD11', // 替换为实际的搜索 URL
                 dataType: 'json',
                 delay: 300,
                 method: 'POST', // 使用 POST 方法
                 data: function (params) {
                     return {
                         query: params.term // search term
                     };
                 },
                 processResults: function (data) {
                     if (data.code == 0) {
                         return {
                             results: data.data.map(function(item) {
                                 return { id: item.id, text: item.categoryName};
                             })
                         };
                     } else {
                         return { results: [] };
                     }
                 },
                 cache: true
             }
         });
             //药师审核选择事件 默认打开
             $('#openCheckYSSid').show();

         // 清空表单字段
         function clearFormFields() {
             $('#category-select').val('').trigger('change');
         }

         // 填充表单字段
         function populateFormFields(data) {
             $('#category-select').val(data.categoryName);//.trigger('change')
         }

    });

    // 监听药师审核选择事件
    function onclickshow() {
        reviewFlag=true;
        $('#openCheckYSSid').show();
    }
    function onclickhide() {
        reviewFlag=false;
        $('#openCheckYSSid').hide();
    }

    // 将后端返回的数据填充到表格中
    function populatePatientTable(datas) {
        var tbody = $('#patient-table tbody');
        tbody.empty(); // 清空现有行
       //var prefix = ctx + "dtp/pmService";
        datas.forEach(function(patient, index) {
            var genderText = patient.gender === 0 ? '男' : '女';
            var row = `
            <tr data-index="${index}">
                <td><input type="radio" name="selectPatient" value="${index}"></td>
                <td>${patient.id}</td>
                <td><a onclick="goPatient(${patient.id})" target="_blank">${patient.name}</a></td>
                <td>${genderText}</td>
                <td>${patient.age || '-'}</td>
                <td>${patient.documentType || '-'}</td>
                <td>${patient.documentNumber || '-'}</td>
                <td>${patient.disease || '-'}</td>
                <td>${patient.phoneNumber || '-'}</td>
                <!-- 添加其他列的数据 -->
            </tr>
        `;
            tbody.append(row);
        });
    }

    // 获取选中的患者数据并存入对象
    function getSelectedPatient() {
        var selectedRow = $('input[name="selectPatient"]:checked').closest('tr');
        if (selectedRow.length === 0) return null;

        var index = selectedRow.data('index');
        return dataList[index];
    }
    function getLastRecipe(patientId){
        var datas=[];
        var data = {
            "patientId":patientId,
        };
        // 初始化表格 getDrugPurchaseList
        $.ajax({
            cache : true,
            type : "POST",
            url : prefix_recipe + "/getLastRecipe",
            data : data,
            async : false,
            error : function(request) {
                $.modal.alertError("系统错误");
            },
            success : function(data) {
              var  shangciObj={};
                shangcigyList=data.data.recipeList;
                if(data.data.recipeList !=null || data.data.recipeList != undefined){
                    initTab(datas=data.data.recipeList)
                }
                if(data.data.recipe!=null){
                    shangciObj=data.data.recipe;

                    $('#hospital').val(shangciObj.hospital);
                    $('#prescribingDoctor').val(shangciObj.prescribingDoctor);
                    $('#department').val(shangciObj.department);
                    $('#attendingDoctor').val(shangciObj.attendingDoctor);

                }else {
                    shangciObj={};
                    $('#hospital').val('');
                    $('#prescribingDoctor').val('');
                    $('#department').val('');
                    $('#attendingDoctor').val('');

                }
                $.operate.successCallback(data);

            }
        });

    }
function initTab(datas){
    var tableId = 'bootstrap-table';
    var tableElement = $('#' + tableId);
    tableElement.bootstrapTable({
        data: datas,
        columns : [

            {field: 'mdmCode', title: '药品编码', align: 'center'},
            {field: 'productName', title: '商品名', align: 'center'},
            {field: 'genericName', title: '通用名', align: 'center'},
            {field: 'specification', title: '规格', align: 'center'},
            {field: 'manufacturerShortName', title: '厂家简称', align: 'center'},
            {field: 'administrationMethod', title: '给药方式', align: 'center'},
            {field: 'realNameStatus', title: '处方取药数量(包装数)', align: 'center'},
            {field: 'singleDoseValue', title: '处方单次剂量数值', align: 'center'},
            {field: 'singleDoseUnit', title: '处方单次剂量单位', align: 'center'},
            {field: 'dosageFrequency', title: '规范用药频次', align: 'center'},
            {field: 'dosageFrequencyDays', title: '用药频次换算使用天数', align: 'center'},
            {field: 'dvalueDays', title: 'D值品用药天数', align: 'center'},
            {field: 'prescriptionNumber', title: '处方编号', align: 'center'},
            // {
            //     title: '操作',
            //     align: 'center',
            //     formatter: function(value, row, index) {
            //         if (row.id) {
            //             var actions = [];
            //             actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.view(\'' + row.id + '\')">购药详情</a> ');
            //             return actions.join('');
            //         } else {
            //             return "";
            //         }
            //     }
            // }
        ]
    });
}
    function getTableData() {
        var tableRows = [];

        $('#drugInfoTable tbody tr').each(function(index, row) {
            var rowData = {
                productId: $(row).data('product-id'),
                mdmCode: $(row).find('td:eq(1)').text(),
                productName: $(row).find('td:eq(2)').text(),
                genericName: $(row).find('td:eq(3)').text(),
                specification: $(row).find('td:eq(4)').text(),
                manufacturerShortName: $(row).find('td:eq(5)').text(),
                administrationMethod: $(row).find('td:eq(6)').text(),
                followUpItem: $(row).find('td:eq(7)').text(),
                coldChainItem: $(row).find('td:eq(8)').text(),
                registeredItem: $(row).find('td:eq(9)').text(),
                charityAidItem: $(row).find('td:eq(10)').text(),
                packaging: $(row).find('td:eq(11)').text(),
                packageQuantity: $(row).find('input[name="packageQuantity"]').val(),
                singleDoseValue: $(row).find('input[name="singleDoseValue"]').val(),
                singleDoseUnit: $(row).find('select[name="singleDoseUnit"]').val(),
                dosageFrequency: $(row).find('select[name="dosageFrequency"]').val(),
                dosageFrequencyDays: $(row).find('input[name="dosageFrequencyDays"]').val(),
                dvalueDays: $(row).find('input[name="dvalueDays"]').val()
            };
            if (rowData.packageQuantity == ''|| rowData.packageQuantity == null|| rowData.packageQuantity == undefined){
                $.modal.alertError("请输入包装数量");
                return;
            }
            if (rowData.singleDoseValue == ''|| rowData.singleDoseValue == null|| rowData.singleDoseValue == undefined){
                $.modal.alertError("请输入单次剂量数值");
                return;
            }
            if (rowData.singleDoseUnit == ''|| rowData.singleDoseUnit == null|| rowData.singleDoseUnit == undefined){
                $.modal.alertError("请输入单次剂量单位");
                return;
            }
            if (rowData.dosageFrequency == ''|| rowData.dosageFrequency == null|| rowData.dosageFrequency == undefined){
                $.modal.alertError("请输入频次");
                return;
            }
            /*if (rowData.dosageFrequencyDays == ''|| rowData.dosageFrequencyDays == null|| rowData.dosageFrequencyDays == undefined){
                $.modal.alertError("请输入频次换算使用天数");
                return;
            }*/
            // 将每一行的数据对象添加到数组中
            tableRows.push(rowData);
        });

        return tableRows;
    }
    function submitHandler() {
        prescriptionNumber='';
        drugsLinkId='';

        var hospital = $("#dtp-form-newcfxx").serializeArray().find(item => item.name === 'hospital');
        if (hospital.value === '') {
            $.modal.alertWarning("请选择请选择医院！");
            return null;
        }
        var prescribingDoctor = $("#dtp-form-newcfxx").serializeArray().find(item => item.name === 'prescribingDoctor');
        if (prescribingDoctor.value === '') {
            $.modal.alertWarning("请输入处方医生！");
            return null;
        }
        var prescriptionDiagnosis = $("#dtp-form-newcfxx").serializeArray().find(item => item.name === 'prescriptionDiagnosis');
        if (prescriptionDiagnosis.value === '') {
            $.modal.alertWarning("请填写处方诊断！");
            return null;
        }
        var prescriptionIssueDate = $("#dtp-form-newcfxx").serializeArray().find(item => item.name === 'prescriptionIssueDate');
        if (prescriptionIssueDate.value === '') {
            $.modal.alertWarning("请选择处方开具日期！");
            return null;
        }

        // 创建一个 FormData 对象用于提交表单数据
        var formData = new FormData();
        // 如果有文件上传，例如处方图片和发票图片
        // var prescriptionImageUrlInput = $('#prescriptionImageUrl')[0];
        // if (prescriptionImageUrlInput.files.length > 0) {
        //     formData.append('prescriptionImageUrl', prescriptionImageUrlInput.files[0]);
        // }
        //
        // var invoiceImageUrlInput = $('#invoiceImageUrl')[0];
        // if (invoiceImageUrlInput.files.length > 0) {
        //     formData.append('invoiceImageUrl', invoiceImageUrlInput.files[0]);
        // }
        // 收集患者信息
        var patientObj = getSelectedPatient();
        if (patientObj) {
            // 添加患者信息到 FormData
            formData.append('patientId', patientObj.id);
            formData.append('patientName', patientObj.name || '');
            formData.append('patientPhone', patientObj.phoneNumber);
            let gender = patientObj.gender; // 获取表单中的性别值
            if (gender ===1) {
                gender = 1; // 如果为空，则设置默认值为 '0'
            }else{
                gender = 0;
            }
            formData.append('gender', gender);
            formData.append('age', patientObj.age);
        }else{
            $.modal.alertError("请先选择患者");
            return;
        }
        // 收集表单中的其他字段，并将其添加到 FormData 中
        $('#dtp-form-newcfxx').find(':input').each(function() {
            var $this = $(this);
            var name = $this.attr('name');
            if (name) { // 确保有 name 属性
                var value = $this.val();
                if (value !== undefined && value !== null && value !== '') { // 确保值不是空
                    formData.append(name, value);
                }
            }
        });
        var selectedOptionsDL = $('#category-select option:selected');
        //var selectedOptionsXL = $('#subcategory-select option:selected');

        var selectedDataDL = selectedOptionsDL.map(function() {
            return {
                id: $(this).val(),
                name: $(this).text()
            };
        }).get();
        const DL = JSON.stringify(selectedDataDL);
        formData.append('dl', DL);
        formData.append('dlanme', DL);
        var reviewingNameInput = $('#pharmacistNameSelect option:selected');
        if($.common.isEmpty(reviewingName) && reviewFlag){
            reviewFlag=false;
            $.modal.alertError("请完成药师审核或选择不开启审核");
            return;
        }
        if(reviewFlag && $.common.isNotEmpty(reviewingName)){
            formData.append('remarks', remarks);
            formData.append('reviewingName', reviewingName);
            formData.append('reviewStatus', reviewStatus);
            formData.append('reviewFormData', reviewFormData);

        }

        var tableRows = [];
        var falg = true;
        $('#drugInfoTable tbody tr').each(function(index, row) {
            var rowData = {
                productId: $(row).data('product-id'),
                mdmCode: $(row).find('td:eq(1)').text(),
                productName: $(row).find('td:eq(2)').text(),
                genericName: $(row).find('td:eq(3)').text(),
                specification: $(row).find('td:eq(4)').text(),
                manufacturerShortName: $(row).find('td:eq(5)').text(),
                administrationMethod: $(row).find('td:eq(6)').text(),
                followUpItem: $(row).find('td:eq(7)').text(),
                coldChainItem: $(row).find('td:eq(8)').text(),
                registeredItem: $(row).find('td:eq(9)').text(),
                charityAidItem: $(row).find('td:eq(10)').text(),
                packaging: $(row).find('td:eq(11)').text(),
                packageQuantity: $(row).find('input[name="packageQuantity"]').val(),
                singleDoseValue: $(row).find('input[name="singleDoseValue"]').val(),
                singleDoseUnit: $(row).find('select[name="singleDoseUnit"]').val(),
                dosageFrequency: $(row).find('select[name="dosageFrequency"]').val(),
                dosageFrequencyDays: $(row).find('input[name="dosageFrequencyDays"]').val(),
                dvalueDays: $(row).find('input[name="dvalueDays"]').val(),

                dosageMax: $(row).find('input[name="dosageMax"]').val(),
                unitMax: $(row).find('input[name="unitMax"]').val(),
                dosageMin: $(row).find('input[name="dosageMin"]').val(),
                unitMin: $(row).find('input[name="unitMin"]').val(),
                dosageNormal: $(row).find('input[name="dosageNormal"]').val(),
                unitNormal: $(row).find('input[name="unitNormal"]').val(),
                packingValue: $(row).find('input[name="packingValue"]').val(),
                packingUnit: $(row).find('input[name="packingUnit"]').val(),
            };
            if (rowData.packageQuantity == ''|| rowData.packageQuantity == null|| rowData.packageQuantity == undefined){
                $.modal.alertError("请输入包装数量");
                falg = false;
                return falg;
            }
            if (rowData.singleDoseValue == ''|| rowData.singleDoseValue == null|| rowData.singleDoseValue == undefined){
                $.modal.alertError("请输入单次剂量数值");
                falg = false;
                return falg;
            }
            if (rowData.singleDoseUnit == ''|| rowData.singleDoseUnit == null|| rowData.singleDoseUnit == undefined){
                $.modal.alertError("请选择单次剂量单位");
                falg = false;
                return falg;
            }
            if (rowData.dosageFrequency == ''|| rowData.dosageFrequency == null|| rowData.dosageFrequency == undefined){
                $.modal.alertError("请选择频次");
                falg = false;
                return falg;
            }
            /* 计算 D 值天数*/
            var dcnum = rowData.singleDoseValue; // 单次用量
            var pcnum = rowData.dosageFrequency; // 用药频次  eg: 一天一次
            // 计算 D 值
            var num = rowData.packageQuantity;  // 买药数量
            var dnum = (num*rowData.dosageFrequencyDays)/(dcnum*pcnum);   //  买药数量 * 包装单位数量 / 频次天数 = D 值天数

            if((dcnum*pcnum)>rowData.dosageMax){
                $.modal.confirm("单次剂量数值频次大于最大值 是否使用默认值?", function() {
                    if (rowData.dosageNormal == ''|| rowData.dosageNormal == null|| rowData.dosageNormal == undefined){
                        dnum = (num*rowData.dosageFrequencyDays)/rowData.dosageMax;
                    }else {
                        dnum = (num*rowData.dosageFrequencyDays)/rowData.dosageNormal;
                    }
                });
            }
            if((dcnum*pcnum)<rowData.dosageMin){
                $.modal.confirm("单次剂量数值频次小于最小值 是否使用默认值?", function() {
                    if (rowData.dosageNormal == ''|| rowData.dosageNormal == null|| rowData.dosageNormal == undefined){
                        dnum = (num*rowData.dosageFrequencyDays)/rowData.dosageMin;
                    }else {
                        dnum = (num*rowData.dosageFrequencyDays)/rowData.dosageNormal;
                    }
                });
            }
            rowData.dvalueDays = dnum;
            // 将每一行的数据对象添加到数组中
            tableRows.push(rowData);
        });
        if (!falg){
            return;
        }
        if (tableRows.length > 0) {
            formData.append('drugData', JSON.stringify(tableRows));
        }else{
            $.modal.alertError("请添加药品");
            return;
        }
        // prescriptionImageUpload 处方
        let prescriptionImageUpload = document.getElementById('prescriptionImageUpload');
        //invoiceImageUpload 发票
        let invoiceImageUpload = document.getElementById('invoiceImageUpload');
        let prescriptionImageFile = prescriptionImageUpload.files[0];
        let invoiceImageFile = invoiceImageUpload.files[0];
        var fd = new FormData();
        var fdi = new FormData();
        var prescriptionImageUrl =$("#prescriptionImageUrl").val();
        var invoiceImageUrl =$("#invoiceImageUrl").val();
        formData.append('prescriptionImageUrl', '');
        formData.append('invoiceImageUrl', '');
        if (prescriptionImageUrl!=''&&prescriptionImageUrl!=null&&prescriptionImageUrl!=undefined){
            formData.append('prescriptionImageUrl', prescriptionImageUrl);
        }
        if (invoiceImageUrl!=''&&invoiceImageUrl!=null&&invoiceImageUrl!=undefined){
            formData.append('invoiceImageUrl', invoiceImageUrl);
        }
        if (prescriptionImageFile && prescriptionImageFile !== '') {
            fd.append('file', prescriptionImageFile); // 'file' 是服务器端用来接收文件的字段名

            $.ajax({
                url: prefix_recipe + "/uploadImg",
                data: fd,
                type: "post",
                processData: false,
                contentType: false,
                success: function(result) {
                    if (result.msg) {
                        formData.append('prescriptionImageUrl', result.msg);
                    }

                    // 上传发票图片
                    if (invoiceImageFile && invoiceImageFile !== '') {
                        fdi.append('file', invoiceImageFile); // 'file' 是服务器端用来接收文件的字段名

                        $.ajax({
                            url: prefix_recipe + "/uploadImg",
                            data: fdi,
                            type: "post",
                            processData: false,
                            contentType: false,
                            success: function(result) {
                                if (result.msg) {
                                    formData.append('invoiceImageUrl', result.msg);
                                }

                                // 更新 CFDJ
                                updateCFDJ(formData);
                            },
                            error: function(xhr, status, error) {
                                $.modal.alertError("上传图片失败");
                            }
                        });
                    } else {
                        // 如果没有发票图片，则直接更新 CFDJ
                        updateCFDJ(formData);
                    }
                },
                error: function(xhr, status, error) {
                    $.modal.alertError("上传图片失败");
                }
            });
        } else if (invoiceImageFile && invoiceImageFile !== '') {
            // 如果只有发票图片需要上传
            fdi.append('file', invoiceImageFile); // 'file' 是服务器端用来接收文件的字段名

            $.ajax({
                url: prefix_recipe + "/uploadImg",
                data: fdi,
                type: "post",
                processData: false,
                contentType: false,
                success: function(result) {
                    if (result.msg) {
                        formData.append('invoiceImageUrl', result.msg);
                    }
                    // 更新 CFDJ
                    updateCFDJ(formData);
                },
                error: function(xhr, status, error) {
                    $.modal.alertError("上传图片失败");
                }
            });
        } else {
            // 如果没有图片需要上传，则直接更新 CFDJ
            updateCFDJ(formData);
        }
    }
    function updateCFDJ(formData) {
        $.ajax({
            cache: false, // 设置为 false 防止缓存
            type: "POST",
            url: prefix_recipe + "/saveCFDJ",
            data: formData,
            processData: false, // 告诉 jQuery 不要处理数据（非常重要）
            contentType: false, // 告诉 jQuery 不要设置 contentType（非常重要）
            async: true, // 异步请求更为推荐，除非有特殊原因需要同步
            error: function (request) {
                $.modal.alertError("操作失败");
            },
            success: function (data) {
                if(data.data.code==200){
                    prescriptionNumber = data.data.prescriptionNumber;
                    drugsLinkId = data.data.drugsLinkId;
                    $.modal.msg(data.msg);

                    $.modal.close();
                    $.modal.msgSuccessReload();
                }else{
                    $.modal.alertError(data.data.msg);
                }

            }
        });
    }
    function openCheckYSSH(){
        //初始化时加载药师信息
        loadPharmacists();
            //$.modal.open("药师审核", prefix_pmService+'/openCheckYSJC'); findRevieForList
        $('#myModal').modal('show');
        //  $.modal.closeTab();
    }
    // 异步加载所有药师信息并填充下拉框
    function loadPharmacists() {
        $.ajax({
            url: prefix_recipe+ "/findRevieForList", // 假设这是获取所有药师的API端点
            type: 'POST',
            cache: false, // 设置为 false 防止缓存
            processData: false, // 告诉 jQuery 不要处理数据（非常重要）
            contentType: false, // 告诉 jQuery 不要设置 contentType（非常重要）
            async: true, // 异步请求更为推荐，除非有特殊原因需要同步
            success: function (data) {
                var select = $('#pharmacistNameSelect');
                // 清空除了默认选项外的所有选项
                select.find('option:not(:first)').remove();
                data.data.forEach(function (pharmacist) {
                    select.append(new Option(pharmacist.pharmacistName, pharmacist.id));
                });
            },
            error: function () {
                $.modal.alertError('加载药师信息失败');
            }
        });
    }

    // 当选择药师后显示密码输入框
    $('#pharmacistNameSelect').change(function () {
        var selectedValue = $(this).val();

        // 如果选择了具体的药师
        if (selectedValue) {
            $('#passwordGroup').show();
            $('#password').val(''); // 清空密码输入框
            $('#checkView').hide(); // 隐藏审核结果部分
            $('#pharmacistVerified').hide(); // 隐藏验证成功的符号
        } else {
            // 如果没有选择任何药师，隐藏所有相关元素
            $('#passwordGroup').hide();
            $('#checkView').hide(); // 确保在切换药师时隐藏审核结果和意见
            $('#pharmacistVerified').hide(); // 隐藏验证成功的符号
            $('#password').val(''); // 清空密码输入框
        }
    });

    // 验证药师密码并显示审核结果部分
    function verifyPassword() {
        var formData = new FormData();

        var pharmacistId = $('#pharmacistNameSelect').val();
        var password = $('#password').val();
        formData.append('id', pharmacistId);
        formData.append('reviewPassword', password);
        $.ajax({
            url: prefix_recipe+"/ReviewCheckInputPassword", // 假设这是验证药师密码的API端点
            type: 'POST',
            data: formData,
            cache: false, // 设置为 false 防止缓存
            processData: false, // 告诉 jQuery 不要处理数据（非常重要）
            contentType: false, // 告诉 jQuery 不要设置 contentType（非常重要）
            async: true, // 异步请求更为推荐，除非有特殊原因需要同步
            success: function (data) {
                if (data.code === 0) {
                    $('#checkView').show();
                    $('#pharmacistVerified').show(); // 显示验证成功的符号
                } else {
                    $.modal.alertError('密码错误');
                    $('#checkView').hide();
                    $('#pharmacistVerified').hide(); // 隐藏验证成功的符号
                }
            },
            error: function () {
                $.modal.alertError('验证失败');
            }
        });
    }
    // 添加点击事件监听器到确认按钮上，用于触发密码验证
    $('#verifyPasswordBtn').click(function () {
        verifyPassword();
    });
    // 提交审核信息
    function submitReview() {
        if ($('#pharmacistNameSelect').val() && $('#password').is(':visible')) {
            verifyPassword();
        } else {
            $.modal.alert('请选择审核药师并输入密码');
        }
        // 如果 checkView 显示，则可以提交表单
        if ($('#checkView').is(':visible')) {
            // 直接从特定的输入元素中获取值
            // 获取审核药师姓名
            var reviewingNameOption = $('#pharmacistNameSelect option:selected');
            var reviewingName1 = reviewingNameOption.text();  // 获取选中的选项文本
            var reviewStatus1 = $('input[name="checkResult"]:checked').val(); // 获取选中的审核结果
            var remarks1 = $('#remarks').val();

            // 检查是否所有必填项都已填写
            if (!reviewingName1) {
                $.modal.alert('请选择审核人');
                return;
            }
            if (!reviewStatus1) {
                $.modal.alert('请选择审核结果');
                return;
            }
            remarks= remarks1;
            reviewingName=reviewingName1;
            reviewStatus=reviewStatus1;

            // 添加到 formData 中
            reviewFormData.append("reviewingName", reviewingName1);
            reviewFormData.append("reviewStatus", reviewStatus1);
            // reviewFormData.append("prescriptionNumber", prescriptionNumber);
            // reviewFormData.append("drugsLinkId", drugsLinkId);
            reviewFormData.append("remarks", remarks1);
            $.modal.msgSuccess('审核信息已保存到处方登记页');
            $('#myModal').modal('hide'); // 关闭弹窗
        }
    }

    // callBack获取父窗口方法（方式二）
    function selectUsersToParentCallBack2(){
        var options = {
            title: '添加处方登记药品',
            width: 1000,
            height: 600,
            url: prefix_yppz + '/getAllProduct',
            callBack: doSubmit2
        };
        $.modal.openOptions(options);
    }
    function doSubmit2(index, layero) {
        var rows = layero.find("iframe")[0].contentWindow.selectTableObject();
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var tableBody = $('#drugInfoTable tbody');

        rows.forEach(function(item) {
            // 动态选择所有列并映射到更具描述性的名称
            var columnsData = {
                productId: item.productId,
                productCode: item.productCode,
                productName: item.productName,
                genericName: item.genericName,
                specification: item.specification,
                packaging: item.packaging,
                manufacturer: item.manufacturer,
                manufacturerAbbreviation: item.manufacturerAbbreviation,
                productStatus: item.productStatus,
                dtpFlag: item.dtpFlag,
                isInsuranceDrug: item.isInsuranceDrug,
                administrationMethod: item.administrationMethod,
                registeredItem: item.registeredItem,
                followUpItem: item.followUpItem,
                coldChainItem: item.coldChainItem,
                flowItem: item.flowItem,
                charityAidItem: item.charityAidItem,

                dosageMax: item.dosageMax,
                unitMax: item.unitMax,
                dosageMin: item.dosageMin,
                unitMin: item.unitMin,
                dosageNormal: item.dosageNormal,
                unitNormal: item.unitNormal,
                packingValue: item.packingValue,
                packingUnit: item.packingUnit,

                dvalueDays: item.dvalueDays,
            };

            // 检查是否已经存在该药品
            if (!isProductExist(columnsData.productId)) {

                // 向表格中添加一行
                var row = `
                <tr data-product-id="${columnsData.productId}">
                    <td><button onclick="deleteRow('${columnsData.productId}')" class="btn btn-danger">删除重选择药品</button></td>
                    <td>${columnsData.productCode}</td>
                    <td>${columnsData.productName}</td>
                    <td class="hidden-column">${columnsData.genericName}</td>
                    <td>${columnsData.specification}</td>
                    <td class="hidden-column">${columnsData.manufacturerAbbreviation}</td>
                    <td class="hidden-column">${columnsData.administrationMethod}</td>
                    <td class="hidden-column">${columnsData.followUpItem === 1 ? '是' : '否'}</td>
                    <td class="hidden-column">${columnsData.coldChainItem === 1 ? '是' : '否'}</td>
                    <td class="hidden-column">${columnsData.registeredItem === 1 ? '是' : '否'}</td>
                    <td class="hidden-column">${columnsData.charityAidItem === 1 ? '是' : '否'}</td>
                    <td class="hidden-column">${columnsData.packaging}</td>

                    <td class="hidden-column"><input name="dosageMax" value="${columnsData.dosageMax}"/></td>
                    <td class="hidden-column"><input name="unitMax" value="${columnsData.unitMax}"/></td>
                    <td class="hidden-column"><input name="dosageMin" value="${columnsData.dosageMin}"/></td>
                    <td class="hidden-column"><input name="unitMin" value="${columnsData.unitMin}"/></td>
                    <td class="hidden-column"><input name="dosageNormal" value="${columnsData.dosageNormal}"/></td>
                    <td class="hidden-column"><input name="unitNormal" value="${columnsData.unitNormal}"/></td>
                    <td class="hidden-column"><input name="packingValue" value="${columnsData.packingValue}"/></td>
                    <td class="hidden-column"><input name="packingUnit" value="${columnsData.packingUnit}"/></td>
                    <td> <input name="packageQuantity" id="packageQuantity${columnsData.productId}" placeholder="取药数量(包装数)" class="styled-input" style="width: 130px;" type="number"></td>
                    <td> <input name="singleDoseValue" id="singleDoseValue${columnsData.productId}" placeholder="单次剂量数值" class="styled-input" style="width: 130px;" type="number"></td>
                    <td>
                        <select name="singleDoseUnit" id="singleDoseUnit${columnsData.productId}" class="styled-input" style="width: 130px;" required>
                            <option value="">请选择</option>
                            <!--<option value="1">mg</option>
                            <option value="2">g</option>
                            <option value="3">片</option>-->
                        </select>
                    </td>
                    <td>
                        <select name="dosageFrequency" id="dosageFrequency${columnsData.productId}" class="styled-input" style="width: 130px;" required>
                            <option value="">请选择</option>
                            <!--<option value="1">一日1次</option>
                            <option value="2">一日2次</option>
                            <option value="3">每天1次</option>
                            <option value="4">每天隔天一次</option>
                            <option value="5">每周2次</option>-->
                        </select>
                    </td>
                    <td> <input name="dosageFrequencyDays" id="dosageFrequencyDays${columnsData.productId}" placeholder="购药包装单位" class="styled-input" style="width: 100px;" type="number"><span id="ycode${columnsData.productId}"></span></td>
                    <td> <input name="dvalueDays" id="dvalueDays${columnsData.productId}" placeholder="系统自动计算" class="styled-input" disabled="" style="width: 100px;" type="number"></td>
                </tr>
            `;
                tableBody.append(row);
                dataInfo(columnsData.productId);
                //bindDosageFrequencyChangeListener(columnsData.productId);
                $('#dosageFrequencyDays'+columnsData.productId).val(columnsData.packingValue);
                $('#ycode'+columnsData.productId).text(columnsData.packingUnit);
            } else {
                $.modal.alertWarning(`药品 [ ${columnsData.productName} ] 已经添加了`);
            }
        });

        $.modal.close(index);
    }

    function dataInfo(productId){
        /*<![CDATA[*/
        var storeTypes = /*[[${@dict.getType('sys_gxhpz_gg_unitall')}]]*/ [];
        /*]]>*/
        /*<![CDATA[*/
        var pcTypes = /*[[${@dict.getType('sys_select_dtp_ysfw_sfpx')}]]*/ [];
        /*]]>*/
        // 获取<select>元素
        var selectElement = document.getElementById('singleDoseUnit' + productId);
        var pcselectElement = document.getElementById('dosageFrequency' + productId);
        storeTypes.forEach(function(item, index){
            var option = document.createElement("option");
            option.value = item.dictValue;
            option.text = item.dictLabel;
            selectElement.add(option);
        })
        pcTypes.forEach(function(item, index){
            var option = document.createElement("option");
            option.value = item.dictValue;
            option.text = item.dictLabel;
            pcselectElement.add(option);
        })
    }
    // 动态绑定用药频次选择事件
    function bindDosageFrequencyChangeListener(productId) {
        $(`#dosageFrequency${productId}`).on('change', function () {
            var selectedValue = $(this).val();
            if (selectedValue) {
                $(`#dosageFrequencyDays${productId}`).val(selectedValue);
            } else {
                $(`#dosageFrequencyDays${productId}`).val('');
            }
        });
    }

    function deleteRow(productId) {
        $.modal.confirm("确认删除该药品吗？", function() {
            // 删除对应行
            $('#drugInfoTable tbody tr[data-product-id="' + productId + '"]').remove();
        });
    }
    function isProductExist(productId) {
        // 检查表格中是否已经存在该药品
        return $('#drugInfoTable tbody tr[data-product-id="' + productId + '"]').length > 0;
    }
    /* 用户管理-新增-选择门店树 */
    function selectDeptTree() {
        var treeId = $("#treeId").val();
        var deptId = $.common.isEmpty(treeId) ? "100" : $("#treeId").val();
        var url = ctx + "system/user/selectDeptTree/" + deptId;
        var options = {
            title: '选择门店',
            width: "380",
            url: url,
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }
    function doSubmit(index, layero){
        var body = $.modal.getChildFrame(index);
        $("#treeId").val(body.find('#treeId').val());
        $("#treeName").val(body.find('#treeName').val());
        $.modal.close(index);
    }

    function goPatient(id){
        $.modal.openTab("患者档案馆", prefix_pmService+'/archivesEdit/'+id);
    }
    function bookbuilding(){
        $.operate.addSetwht('快速建档','dtp/pmService/archivesAdd',800,800)
        //$.modal.open("快速建档", prefix_pmService+'/archivesAdd');
    }
    function resetPre() {
        resetDate();
        $("#dtp-form-hxcx")[0].reset();
        $("#query").val("");
    }
    function search_hz() {
        var query = $('#query').val();
        // 如果输入为空，清空 dValueId 输入框并停止进一步操作
        if (!query) {
            $('#query').val('');
            var tbody = $('#patient-table tbody');
            tbody.empty(); // 清空现有行
            return;
        }

        // 使用防抖机制延迟发送请求
        // 发送 AJAX 请求到服务器查询数据
        hzparam={query:query};//模拟微信扫码获取微信openId
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix_pmService+'/slectPatientByNameOrPhoneOrIdCard', // 替换为实际的搜索 URL
            data: hzparam,
            async: false,
            success: function (data) {

                if(data.code==0){
                    dataList=[];
                    populatePatientTable(data.data);
                    dataList=data.data;
                    // 如果有且只有一条记录，默认选中这条记录
                    if (data.data.length === 1) {
                        setTimeout(function() {
                            $('input[name="selectPatient"]').first().prop('checked', true).trigger('change');
                        }, 0); // 确保DOM已经完全渲染
                    }
                    if (data.data.length <=0) {
                        var tbody = $('#patient-table tbody');
                        tbody.empty(); // 清空现有行
                        $.modal.confirm("未找到患者 点击确定可快速建档", function() {
                            // 快速建档
                            bookbuilding();
                        });




                    }
                        // // 如果找到匹配的数据，更新输入框
                        // $('#patientId').val(data.data.id);
                        // $('#patientName').val(data.data.name);
                        // var gender = data.data.gender;
                        // $('#gender').val(gender === 1 ? '男' : gender === 0 ? '女' : '');
                        // $('#age').val(data.data.age);
                        // var patientId =  data.data.id;

                        // if(patientId !='' && patientId != null){
                        //     //查询出对应患者的上一次处方登记信息
                        //     getLastRecipe(patientId);
                        // }

                }else{
                    // // 清空表格中的所有数据行
                    // $('#patientId').val('');
                    // $('#patientName').val('');
                    // $('#gender').val('');
                    // $('#age').val('');
                    // $('#query').val('');
                    // getLastRecipe(0);
                    $.modal.alertWarning(`未找到患者 可快速建档`);
                    bookbuilding();
                    var tbody = $('#patient-table tbody');
                    tbody.empty(); // 清空现有行
                }

            },
            error: function(error) {
                var tbody = $('#patient-table tbody');
                tbody.empty(); // 清空现有行
                // 清空 dValueId 输入框
                $('#query').val('');
            }
        });
    }
</script>
<style>

    .ibox {
        width: auto;
        height: 370px;
        overflow: auto; /* 当内容超过指定尺寸时显示滚动条 */
    }

    .fixed-layout-table {
        width: 100%;
        border-collapse: collapse; /* 减少单元格间距 */
    }

    .fixed-layout-table thead th {
        position: sticky;
        top: 0;
        background-color: #f8f9fa; /* 表头背景颜色 */
        z-index: 1;
    }

    /* 隐藏列的样式 */
    .hidden-column {
        display: none;
    }


    .hidden {
        display: none;
    }
    /*.ibox {*/
    /*    width: 700px;*/
    /*    margin-bottom: 20px;*/
    /*    border: 1px solid #e7eaec;*/
    /*    border-radius: 4px;*/
    /*}*/
    .ibox-title {
        background-color: #e6e3da;
        border-bottom: 1px solid #e7eaec;
        padding: 10px 15px;
        font-size: 16px;
        width: 1540px;
    }
    .ibox-content {
        padding: 15px;
    }
    .ibox-content h4 {
        margin-top: 0;
    }

    .form-horizontal .form-group {
        margin-right: 384px;
        margin-left: 3px;
    }
    input[type=file] {
        display: none;
    }
    .form-group {
        margin-bottom: -1px;
    }
    /* 添加一些基础样式 */
    body {
        font-family: Arial, sans-serif;
    }
    /* 使用ID选择器来确保样式仅应用于特定表格 */
    #drugInfoTable {
        /*width: 500px;*/
        border-collapse: collapse;
    }

    /* 使用后代选择器来确保样式仅应用于该表格内的th和td元素 */
    #drugInfoTable th, #drugInfoTable td {
        text-align: left;
        padding: 5px;
        border-bottom: 1px solid #ddd;
    }

    /* 使用后代选择器来确保样式仅应用于该表格内的tr元素 */
    #drugInfoTable tr:nth-child(even) {
        background-color: #f2f2f2;
    }

    /* 修正了宽度设置，因为宽度通常不应该应用于行（tr），而是应用于单元格（td或th） */
    #drugInfoTable tr:nth-child(even) td {
        width: auto; /* 根据内容自动调整宽度 */
    }
    .hidden-column {
        display: none;
    }


    .customize-table {
        width: 100%;
        border-collapse: collapse;
    }

    .customize-table th, .customize-table td {
        border: 1px solid #ddd;
        padding: 8px;
    }

    .customize-table th {
        background-color: #f2f2f2;
        text-align: left;
    }

    .customize-table tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    .customize-table tr:hover {
        background-color: #ddd;
    }

    /* 新增：选中行的样式 */
    .customize-table tr.selected {
        background-color: #a9a9c5;
        color: white; /* 确保文字可见 */
    }
    .verified-symbol {
        color: green;
        font-size: 16px;
        margin-left: 5px;
    }
    .fileinput-preview.thumbnail {
        display: flex;
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
        text-align: center; /* 确保文本内部也居中 */
        position: relative;
        background-color: #f5f5f5; /* 设置背景颜色以更好地区分 */
        border: 2px dashed #ccc; /* 添加虚线边框 */
        color: #999; /* 文字颜色 */
        font-size: 14px; /* 文字大小 */
    }

    .centered-content {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .plus-sign {
        margin-top: 5px;
        font-size: 24px;
        font-weight: bold;
    }
    /* 隐藏初始的大图 */
    .preview-large {
        display: none;
        position: absolute;
        border: 1px solid #ccc;
        background-color: #fff;
        z-index: 1000;
    }

    /* 确保预览框在特定容器内 */
    .customize-form-group-container {
        position: relative;
    }
    .fileinput .fileinput-preview {
        background-image: none !important;
        background-color: transparent !important;
    }
</style>
</body>
</html>




