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

<div class="col-sm-12 search-collapse">
    <div id="hzjdflag">
        <a class="btn btn-info btn-rounded btn-sm" onclick="addArchivesCallback()">&nbsp;快速建档</a>
        <!--<a class="btn btn-info btn-rounded btn-sm" onclick="$.operate.addSetwht('添加患者信息','dtp/pmService/addArchivesCallback',800,800)">&nbsp;快速建档</a>-->
        <!-- addArchivesCallback()提示信息<a class="btn btn-info btn-rounded btn-sm" onclick="$.operate.addSetwht('添加患者信息','dtp/pmService/addArchivesCallback',800,750)">&nbsp;快速建档</a> -->
        <span id="patientFlagMessage" style="display:none;" class="text-danger"></span>
    </div>

    <form id="dtp-form-newcfxx" class="customize-search-form">
        <div class="customize-form-group-container">
            <div class="customize-form-group">
                <label>患者姓名:</label>
                <input name="patientName" placeholder="患者姓名" id="patientName" readonly  class="styled-input" type="text"  th:value="${patientName}">
                <input type="hidden" id="id" class="styled-input" name="id" th:value="${id}">
                <input type="hidden" id="patientId" class="styled-input"  name="patientId" th:value="${patientId}">
                <input type="hidden" id="prescriptionNumber" name="prescriptionNumber" th:value="${prescriptionNumber}">
                <input type="hidden" id="drugsLinkId" name="drugsLinkId" th:value="${drugsLinkId}">
                <input type="hidden" id="status" placeholder="处方状态"  name="status" th:value="${status}">


            </div>
            <div class="customize-form-group">
                <label>手机号码:</label>
                <input type="text" id="patientPhone"  placeholder="手机号" class="styled-input" readonly th:value="${patientPhone}">
            </div>
            <div class="customize-form-group">
                <label>性别:</label>
                <select name="gender1"  id="gender1" class="styled-input" th:with="type=${@dict.getType('sys_user_sex')}" disabled="true">
                    <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                            th:selected="${dict.dictValue} == ${gender}" ></option>
                </select>
<!--                <input name="gender1" placeholder="性别" id="gender1" readonly  class="styled-input" type="text" th:value="${gender}">-->
            </div>
            <div class="customize-form-group">
                <label>年龄:</label>
                <input name="age1" placeholder="年龄" id="age1" readonly  class="styled-input" type="text" th:value="${age}">
            </div>
            <div class="customize-form-group">
                <label class="is-required">医院:</label>
                <select id="hospital-select"  name="hospital" class="styled-input 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">-->
<!--                <label class="is-required">临床诊断:</label>-->
<!--                <input name="clinicalDiagnosis" id="clinicalDiagnosis" 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="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="审核药师姓名" readonly   th:value="${reviewingName}" class="styled-input" type="text">
            </div>
            <div class="customize-form-group">
                <label>临床诊断：</label>
                <select id="category-select"   class="styled-input edit_inputs 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" 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="modal inmodal fade" id="myModal2" tabindex="-1" role="dialog" >
    <div class="modal-dialog modal-lg" style="width: 1000px">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">快速建档</h4>
                <!--<small class="font-bold">这里可以显示副标题。</small>-->
            </div>
            <div class="modal-body">
                <form id="form-server-add">
                    <div class="customize-form-group-container">
                        <label class="font-noraml">身份证上传</label>
                        <div class="new-contentarea tc">
                            <a href="javascript:void(0)" class="btn btn-xs btn-primary"><label for="inputImage" >上传图像</label> </a>
                            <input type="file" name="avatar" id="inputImage" onchange="uploadImage(this)" accept="image/*"/>
                        </div>
                        <div class="ibox2-title" style="align-items: center;">
                            <img id="uploadedImage" src="" style="max-width: 50%;display: block;margin-left: 21%;">
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label is-required">姓名：</label>
                            <input name="name" id="name" placeholder="请输入姓名" class="styled-input" type="text" maxlength="30" required>
                            <input type="hidden" name="idCardImg" id="idCardImg" value="">
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label is-required">性别：</label>
                            <select name="gender" id="gender" class="styled-input" th:with="type=${@dict.getType('sys_user_sex')}" required>
                                <option value="">请选择</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"
                                ></option>
                            </select>
                        </div>
                        <div class="customize-form-group select-time">
                            <label class="col-sm-1 control-label">出生年月：</label>
                            <div class="input-group select-time">
                                <input name="dateBirth" placeholder="出生年月" class="time-input time-input2" type="text" id="dateBirth" disabled>
                            </div>
                        </div>
                        <div class="customize-form-group select-time">
                            <label class="col-sm-1 control-label">年龄：</label>
                            <div class="input-group select-time">
                                <input name="age" id="age" placeholder="年龄" class="styled-input" type="text" maxlength="30" disabled>
                            </div>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label is-required">联系方式：</label>
                            <input name="phoneNumber" id="phoneNumber" placeholder="请输入手机号" class="styled-input isPhone" type="text" maxlength="11"  required>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">联系人手机号：</label>
                            <input name="contactPhone" placeholder="请输入联系人手机号" class="styled-input isPhone" type="text" maxlength="11"  required>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">证件类型：</label>
                            <select name="documentType" id="documentType"  class="styled-input" th:with="type=${@dict.getType('sys_select_dtp_ysfw_zjlx')}" required>
                                <option>请选择</option>
                                <option th:each="dict : ${type}" th:selected="${dict.dictLabel=='居民身份证'}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}"></option>
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">联系人姓名：</label>
                            <input name="contactName" placeholder="请输入联系人姓名" class="styled-input" type="text" maxlength="30"  required>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">证件号码：</label>
                            <input name="documentNumber" id="documentNumber" placeholder="请输入证件号码" class="styled-input" type="text" maxlength="30"  required>
                        </div>
                        <div class="customize-form-group edit select-time">
                            <label class="col-sm-1 control-label is-required">首次确诊时间：</label>
                            <input name="timeFirstDiagnosis" id="timeFirstDiagnosis" placeholder="首次确诊时间" class="time-input time-input2"  type="text" >
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">配送地址：</label>
                            <input name="addr" placeholder="配送地址"  id="addr" class="styled-input" type="text">
                        </div>



                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">肿瘤发病部位疾病：</label>
                            <select id="category-select1"   class="styled-input select2-multiple edit_inputs" multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">肿瘤治疗并发症与合并症：</label>
                            <select id="category-select2" class="styled-input select2-multiple edit_inputs" multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">风湿免疫疾病名称：</label>
                            <select id="category-select3"   class="styled-input select2-multiple edit_inputs" multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">罕见病疾病：</label>
                            <select id="category-select4" class="styled-input select2-multiple edit_inputs" multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">感染类疾病：</label>
                            <select id="category-select5"   class="styled-input select2-multiple edit_inputs" multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                        <div class="customize-form-group">
                            <label class="col-sm-1 control-label">临时慢病：</label>
                            <select id="category-select6"   class="styled-input select2-multiple edit_inputs " multiple placeholder="请选择或输入搜索">
                            </select>
                        </div>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitArchives()">保存</button>
            </div>
        </div>
    </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 :: bootstrap-fileinput-js" />-->
<th:block th:include="include :: jasny-bootstrap-js" />
<th:block th:include="include :: bootstrap-table-fixed-columns-js" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: select2-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 patientId;
    var name;
    var age;
    var gender;
    var remarks;
    var reviewingName;
    var reviewStatus;
    var reviewFlag=false;
    var data;
    var patientFlag = true;//患者是否建档
    var shangcigyList = [];
    var dataList = [];
    var reviewFormData = new FormData();
    var selectdataList = [];
    /*<![CDATA[*/
    var dl = /*[[${dl}]]*/ '';
    /*]]>*/
    /*<![CDATA[*/
    var xl = /*[[${xl}]]*/ '';
    /*]]>*/

    /*<![CDATA[*/
    var hospitals = /*[[${hospital}]]*/ '';
    /*]]>*/


    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 - 300; // 如果右侧空间不足，则放在左侧
            if (top + largePreviewHeight > winHeight) top = e.pageY - largePreviewHeight; // 如果底部空间不足，则放在上方

            largePreview.style.left = left + 'px';
            largePreview.style.top = top+400 + '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 ; // 尝试放置在鼠标右侧
            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 () {

        // 监听文件选择变化事件
        $("#prescriptionImageUpload").on('change', function() {
            var file = this.files[0];
            if (file) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    // 更新预览区域的背景图片
                    $('#prescriptionImagePreview .fileinput-preview').css('background-image', 'url(' + e.target.result + ')');
                    $('#prescriptionImagePreview .centered-content').hide(); // 隐藏加号图标
                };
                reader.readAsDataURL(file);
            } else {
                // 如果没有选择文件，则恢复默认状态
                $('#prescriptionImagePreview .fileinput-preview').css('background-image', '');
                $('#prescriptionImagePreview .centered-content').show(); // 显示加号图标
            }
        });
        //初始化查询患者是否建档
        var status = $('#status').val();
        if(status == 4){
            initCheckPatient();
        }
        if (!patientFlag) {
            $('#patientFlagMessage').text('该患者未建档，请先建档后在继续操作!。').show();
        } else {
            $('#patientFlagMessage').hide();
        }
        // 获取所有的输入元素（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 但是会出现 第一个删除出现问题有空格
        });

        $('#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);

                });
                // 设置默认选中的 dl 选项
                options.val(hospitals).trigger('change');
                /*$('#category-select').select2({
                    placeholder: "请选择或直接输入搜索",
                    //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
                });*/
                // 加载对应的 xl 数据

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


        // 直接使用 dl 数据预填充下拉列表
        var dlParsed = JSON.parse(dl);
        if (Array.isArray(dlParsed)) {
            var dlIds = dlParsed.map(function (item) {
                return item.id;
            }); // 转换为 ID 数组

            // 添加 dl 中的选项到下拉列表
            $.each(dlParsed, function (index, item) {
                $('<option>', {
                    value: item.id,
                    text: item.name
                }).appendTo($('#category-select'));
            });

            // 设置默认选中的 dl 选项
            $('#category-select').val(dlIds).trigger('change');
        }

        // 发送 AJAX 请求获取疾病大类数据
        // 初始化 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,
                error: function (xhr, status, error) {
                    $.modal.alertError("获取疾病信息失败");
                }
            }
        });
        var reviewingName = $('#reviewingName').val();
        if($.common.isNotEmpty(reviewingName)){
            reviewFlag=true;
            $('#openCheckYSSid').hide();
        }else{
            reviewFlag=false;
            $('#openCheckYSSid').show();
        }
    });
    function updatePatientFlag(flagValue) {
        patientFlag = flagValue;

        if (!patientFlag) {
            $('#patientFlagMessage').text('该患者未建档，请先建档后在继续操作!').show();
        } else {
            $('#patientFlagMessage').hide();
        }
    }
    function formatGender(value) {
        switch (value) {
            case 0:
                $('#gender1').val(value);
                break;
            case 1:
                $('#gender1').val(value);
                break;
            default:
                $('#gender1').val('未知');
                break;
        }
    }
    //检查患者是否存在
    function initCheckPatient() {
        var formData = new FormData();
        var patientName = $('#patientName').val();
        var patientPhone = $('#patientPhone').val();
        formData.append("name", patientName);
        formData.append("phoneNumber", patientPhone);
        $.ajax({
            cache: false, // 设置为 false 防止缓存
            type: "POST",
            url: prefix_pmService+ "/slectPatientByNameAndPhone", // 假设这是获取所有药师的API端点
            data: formData,
            processData: false, // 告诉 jQuery 不要处理数据（非常重要）
            contentType: false, // 告诉 jQuery 不要设置 contentType（非常重要）
            async: true, // 异步请求更为推荐，除非有特殊原因需要同步
            error: function (request) {
                $.modal.alertError("检查患者是否存在失败");
            },
            success: function (data) {
                if(data.code==0){
                    patientFlag = true;
                    patientId = data.data.id;
                    name = data.data.name;
                    age = data.data.age;
                    gender = data.data.gender;
                    //性别格式化
                    formatGender(gender);
                    $('#gender1').val(data.data.gender);
                    $('#age1').val(data.data.age);
                    $('#patientPhone').val(data.data.phoneNumber);
                    $('#patientName').val(data.data.name);

                    //初始化查询患者最近购药信息
                    getLastRecipe(patientId);
                   // $.modal.msg(data.msg);
                }else{
                    patientFlag = false;
                    updatePatientFlag(false);
                    //$.modal.alertError("查询无数据,该患者未建档，请先建档后在继续操作");
                    $.modal.confirm("该患者未建档 ,请先建档后在继续操作!,点击确定可快速建档", function() {
                        // 快速建档
                        bookbuilding();
                    });

                }

            }
        });

    }


    // 将后端返回的数据填充到表格中
    function populatePatientTable(datas) {
        var tbody = $('#patient-table tbody');
        tbody.empty(); // 清空现有行

        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>${patient.name}</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 submitHandler() {
        if(!patientFlag){
            //$.modal.alertError("该患者未建档，请先建档后在继续操作");
            $.modal.confirm("该患者未建档 ,请先建档后在继续操作!,点击确定可快速建档", function() {
                // 快速建档
                bookbuilding();
            });
            return;
        }
        // 创建一个 FormData 对象用于提交表单数据
        var formData = new FormData();
        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 中
        $('#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 selectedhospital = $('#hospital-select option:selected');
        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();  // 获取的数据格式 [{ id: "2", name: "肿瘤治疗并发症与合并症名称" }, { id: "3", name: "风湿免疫疾病名称库" }]
        var selectedDataXL = selectedOptionsXL.map(function () {
            return {
                id: $(this).val(),
                name: $(this).text()
            };
        }).get();  // 获取的数据格式 [{ id: "2", name: "肿瘤治疗并发症与合并症名称" }, { id: "3", name: "风湿免疫疾病名称库" }]
        var selectedhospitals = selectedhospital.map(function () {
            return {
                id: $(this).val(),
                name: $(this).text()
            };
        }).get();
        const hospitals = JSON.stringify(selectedhospitals);
        const DL = JSON.stringify(selectedDataDL);
        const XL = JSON.stringify(selectedDataXL);
        formData.append('dl', DL);
        formData.append('xl', XL);
        formData.append('dlanme', DL);
        formData.append('xlname', XL);
        // 将药物数据序列化为 JSON 字符串并添加到 FormData 中
        var tableRows = [];
        var falg = true;
        var ts_msg = '';
        $('#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.dosageFrequencyDays == ''|| rowData.dosageFrequencyDays == null|| rowData.dosageFrequencyDays == undefined){
                $.modal.alertError("购药包装单位为空,请到药品库设置包装单位后再操作");
                falg = false;
                return falg;
            }
            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) {
                ts_msg = '单次剂量数值频次大于 最大值 已使用默认值';
                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) {
                ts_msg = '单次剂量数值频次小于 最小值 已使用默认值';
                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;
        }
        var id = $('#id').val();
        var prescriptionNumber = $('#prescriptionNumber').val();
        var drugsLinkId = $('#drugsLinkId').val();
        var status = $('#status').val();
        if (id != '') {
            formData.append('id', id);
            formData.append('status', status);
            formData.append('prescriptionNumber', prescriptionNumber);
            formData.append('drugsLinkId', drugsLinkId);
        } else {
            $.modal.alertError("数据异常！请联系管理员!");
            return;
        }
        var reviewingNameInput = $('#reviewingName').val();
        if($.common.isEmpty(reviewingNameInput) && !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);

        }
        formData.append('age',  $('#age1').val());
        formData.append('gender',  $('#gender1').val());
        formData.append('patientPhone',  $('#patientPhone').val());
        formData.append('patientName',  $('#patientName').val());
        // 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 + "/updateCFDJ",
            data: formData,
            processData: false, // 告诉 jQuery 不要处理数据（非常重要）
            contentType: false, // 告诉 jQuery 不要设置 contentType（非常重要）
            async: false, // 异步请求更为推荐，除非有特殊原因需要同步
            error: function(request) {
                $.modal.alertError("操作失败");
            },
            success: function(data) {
                $.modal.alertSuccess(data.msg);
                $.modal.closeTab();
                window.location.reload();
            }
        });
    }

    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);
            reviewFlag=true;
            $.modal.msgSuccess('审核信息已保存到处方登记页');
            $('#openCheckYSSid').hide();
            $('#myModal').modal('hide'); // 关闭弹窗
        }
    }
    // 监听药师审核选择事件
    function onclickshow() {
        reviewFlag=false;
        $('#openCheckYSSid').show();
    }
    function onclickhide() {
        reviewFlag=true;
        $('#openCheckYSSid').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.productCode,
                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,
            };

            // 检查是否已经存在该药品
            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"  disabled 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: 80px;" type="number"></td>
                </tr>
            `;
                tableBody.append(row);
                dataInfo(columnsData.productId)
                $('#dosageFrequencyDays' + columnsData.productId).val(columnsData.packingValue);
                $('#ycode' + columnsData.productId).text(columnsData.packingUnit);
                //bindDosageFrequencyChangeListener(columnsData.productId);
            } 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 bookbuilding(){
        loadAchievs();
        $('#myModal2').modal('show');
        //$.operate.addSetwht('快速建档', prefix_pmService + '/archivesAdd',800,800)
    }
    function resetPre() {
        resetDate();
        $("#dtp-form-hxcx")[0].reset();
        $("#query").val("");
    }

    function search_hz() {
        var query = $('#query').val();
        // 如果输入为空，清空 dValueId 输入框并停止进一步操作
        if (!query) {
            $('#query').val('');
            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) {
                // 清空 dValueId 输入框
                $('#query').val('');
            }
        });
    }

    /* 这里是去查询 使用药的信息*/
    $(document).ready(function () {
        var id = $('#id').val();
        var datas = [];
        var data = {
            "id": id,
        };
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix_recipe + "/getLastRecipeInfo",
            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) {
                    initTabShow(datas = data.data.recipeList)
                }
                if (data.data.recipe != null) {
                    shangciObj = data.data.recipe;
                    // 动态填充表单字段
                    $.each(shangciObj, function (key, value) {
                        $('#' + key).val(value);
                        if (key == "gender") {
                            if (value == 0) {
                                value = "男";
                            } else {
                                value = "女";
                            }
                            $('#' + key).val(value);
                        }
                    });
                }
            }
        });
    });

    function initTabShow(datas) {
        datas.forEach(function (item) {
            var tableBody = $('#drugInfoTable tbody');
            // 动态选择所有列并映射到更具描述性的名称
            var columnsData = {
                productId: item.mdmCode,
                productCode: item.mdmCode,
                productName: item.productName || "",
                genericName: item.genericName || "",
                specification: item.specification,
                packaging: item.packaging,
                manufacturer: item.manufacturer,
                manufacturerAbbreviation: item.manufacturerShortName,
                productStatus: item.productStatus,
                dtpFlag: item.dtpFlag,
                isInsuranceDrug: item.isInsuranceDrug,
                administrationMethod: item.administrationMethod,
                registeredItem: item.registeredItem,
                followUpItem: item.followUpItem,
                coldChainItem: item.coldChainItem,
                flowItem: item.flowItem,
                packageQuantity: item.packageQuantity,
                singleDoseValue: item.singleDoseValue,
                singleDoseUnit: item.singleDoseUnit,
                dosageFrequency: item.dosageFrequency,
                dosageFrequencyDays: item.dosageFrequencyDays,
                charityAidItem: item.charityAidItem,

                dosageMax: item.dosage_max,
                unitMax: item.unit_max,
                dosageMin: item.dosage_min,
                unitMin: item.unit_min,
                dosageNormal: item.dosage_normal,
                unitNormal: item.unit_normal,
                packingValue: item.packing_value,
                packingUnit: item.packing_unit,

                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" value="${columnsData.packingValue}" id="dosageFrequencyDays${columnsData.productId}" placeholder="购药包装单位" class="styled-input" disabled 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: 80px;" type="number"><span id="defaultNum${columnsData.productId}" style="color: red"></span></td>
                </tr>
            `;
                tableBody.append(row);
                dataInfo(columnsData.productId)
                //bindDosageFrequencyChangeListener(columnsData.productId);
                $('#packageQuantity' + columnsData.productId).val(columnsData.packageQuantity);
                $('#dvalueDays' + columnsData.productId).val(columnsData.dvalueDays);
                $('#singleDoseValue' + columnsData.productId).val(columnsData.singleDoseValue);
                // 设置 select 元素的值，这将会选中 value 与 columnsData.singleDoseValue 匹配的 option
                $('#singleDoseUnit' + columnsData.productId).val(columnsData.singleDoseUnit);
                $('#dosageFrequency' + columnsData.productId).val(columnsData.dosageFrequency);
                $('#dosageFrequencyDays' + columnsData.productId).val(columnsData.packingValue);
                $('#ycode' + columnsData.productId).text(columnsData.packingUnit);
                var dcnum = columnsData.singleDoseValue; // 单次用量
                var pcnum = columnsData.dosageFrequency; // 用药频次  eg: 一天一次
                // 计算 D 值
                if ((dcnum * pcnum) > columnsData.dosageMax) {
                    $('#defaultNum' + columnsData.productId).text("默认值");
                }
                if ((dcnum * pcnum) < columnsData.dosageMin) {
                    $('#defaultNum' + columnsData.productId).text("默认值");
                }
            } else {
                $.modal.alertWarning(`药品 [ ${columnsData.productName} ] 已经添加了`);
            }
        });
    }




   //患者信息


    function addArchivesCallback(){
        $('#myModal2').modal('show');
        //初始化信息
        loadAchievs();
    }

    function loadAchievs(){
        $('#documentNumber').on('input', function() {
            idCard();
        });
        for (var i = 1; i < 7; i++) {
            // 初始化 Select2 插件
            $('#category-select'+i).select2({
                placeholder: "请选择或直接输入搜索",
                //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
            }).css({
                'z-index': '9999',
                'position': 'relative'
            });
        }
        // 肿瘤发病部位疾病名称 1
        // 肿瘤治疗并发症与合并症名称 2
        // 风湿免疫疾病名称库 3
        // 罕见病疾病名称  4
        // 感染类疾病名称 5
        // 临时慢病名称 6
        // 发送 AJAX 请求获取疾病大类数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                // 获取所有的 select 元素
                var selects = [
                    $('#category-select1'),
                    $('#category-select2'),
                    $('#category-select3'),
                    $('#category-select4'),
                    $('#category-select5'),
                    $('#category-select6')
                ];
                // 清空已有选项（除了第一个默认选项）
                selects.forEach(function(select) {
                    select.find('option').not(':first').remove();
                });
                // 添加默认选项到每个下拉列表
                selects.forEach(function(select) {
                    if (!select.find('option:first').length) { // 检查是否已经有默认选项
                        $('<option>', {
                            value: '',
                            text : '请选择疾病'
                        }).prependTo(select); // 使用 prependTo 确保它成为第一个选项
                    }
                });
                // 解析 dl 数据并获取 ID 数组
                /*<![CDATA[*/
                var dl = /*[[${dl}]]*/ '';
                /*]]>*/
                var dlParsed = JSON.parse(dl);
                var dlIds = Array.isArray(dlParsed) ? dlParsed.map(item => item.id.toString()) : [];
                // 遍历返回的数据并添加选项
                $.each(data.value || [], function(index, item) {
                    var selectIndex = item.dict_key-1; // 假设 dict_key 是从 1 开始的索引
                    if (selectIndex >= 0 && selectIndex < selects.length) {
                        $('<option>', {
                            value: item.id,
                            text : item.categoryName
                        }).appendTo(selects[selectIndex]);
                        // 设置选中的值（仅当 dlIds 包含该项 id 时）
                        if (dlIds.includes(item.id.toString())) {
                            selects[selectIndex].val(item.id).trigger('change');
                        }
                    }
                });
                // 如果使用 Select2 插件，则初始化或刷新它们
                selects.forEach(function(select) {
                    select.trigger('change');
                });
            },
            error: function(xhr, status, error) {
                $.modal.alertError("解析疾病失败");
            }
        });
    }


    // 示例使用
    function submitArchives() {
        var documentType= $("#documentType").val();
        if(documentType=="居民身份证") {
            var IDCard= $("#documentNumber").val();
            if (IDCard == null || IDCard == "" || IDCard == undefined){
                $.modal.alertError("请输入身份证号码")
                return;
            }
            if (validateIDCard(IDCard)==false) {
                $.modal.alertError("身份证号码格式不正确，请重新输入！")
                return;
            }
        }
        var gender= $("#gender").val()
        if (gender==null || gender=="" || gender==undefined) {
            $.modal.alertError("请选择性别")
            return ;
        }
        var timeFirstDiagnosis= $("#timeFirstDiagnosis").val();
        if (timeFirstDiagnosis==null || timeFirstDiagnosis=="" || timeFirstDiagnosis==undefined) {
            $.modal.alertError("请选择首次确诊时间")
            return ;
        }
        var phoneNumber= $("#phoneNumber").val()
        if (phoneNumber==null || phoneNumber=="" || phoneNumber==undefined) {
            $.modal.alert("请输入联系方式")
            return ;
        }

        add();
    }

    function add() {
        var data = $("#form-server-add").serializeArray();
        // 获取所有选中的选项并处理数据
        var selectedDataDL = [];
        for (let i = 1; i <= 6; i++) {
            var selectedOptionsDL = $(`#category-select${i} option:selected`);
            if (selectedOptionsDL.length > 0) {
                selectedOptionsDL.each(function() {
                    selectedDataDL.push({
                        id: $(this).val(),
                        name: $(this).text(),
                    });
                });
            }
        }
        var hasSelection = false;
        if (selectedDataDL.length > 0) {
            hasSelection = true;
        }

        var DL = JSON.stringify(selectedDataDL);
        if (!hasSelection) {
            $.modal.alert('请至少选择一个疾病选项！');
            return;
        }
        data.push({name: "dl", value: DL});
        data.push({name: "age", value: $("#age").val()});
        data.push({name: "dateBirth", value: $("#dateBirth").val()});
        $.ajax({
            cache : true,
            type : "POST",
            url : ctx + "dtp/pmService/archivesAdd",
            data : data,
            async : false,
            error : function(request) {
                $.modal.alertError("系统错误");
            },
            success : function(responseData) {
                $('#patientPhone').val($("#phoneNumber").val())
                $('#patientName').val($("#name").val());
                $('#age1').val($("#age").val());
                $('#gender1').val($("#gender").val());
                $('#patientFlagMessage').hide();
                patientFlag = true;
                $('#myModal2').modal('hide'); // 关闭弹窗
            }
        });
    }

    function uploadImage(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#uploadedImage').attr('src', e.target.result).show();
                // 调用 OCR 识别
                recognizeIdCard(input.files[0]);
            };
            reader.readAsDataURL(input.files[0]);
            // 直接将文件对象传递给 sendImageToServer
            sendImageToServer(input.files[0]);
        }
    }
    function sendImageToServer(file) {
        var formdata = new FormData();
        formdata.append("idcardImgfile", file);
        $.ajax({
            url: prefix_pmService + "/updateIdcardImg",
            data: formdata,
            type: "post",
            processData: false,
            contentType: false,
            success: function(result) {
                $("#idCardImg").val(result.msg)
            },
            error: function(xhr, status, error) {
                console.error("Error uploading image:", error);
            }
        });
    }

    function recognizeIdCard(file) {
        const formData = new FormData();
        formData.append('image', file);
        $.ajax({
            url: prefix_pmService + "/idCard",
            data: formData,
            type: 'post',
            processData: false,
            contentType: false,
            success: function(result) {
                if (result.data.words_result) {
                    const name =result.data.words_result.姓名.words;
                    const idNumber = result.data.words_result.公民身份号码.words;
                    const gender = result.data.words_result.性别.words;
                    const address = result.data.words_result.住址.words;
                    const dateBirth = result.data.words_result.出生.words;
                    //const nation = result.data.words_result.名族.words;
                    if (gender == "男"){
                        $("#gender").val("0");
                    }else if (gender == "女"){
                        $("#gender").val("1");
                    }else if (gender == "未知"){
                        $("#gender").val("2");
                    }
                    // 将提取的信息填充到表单中
                    document.getElementById('name').value = name;
                    document.getElementById('documentNumber').value = idNumber;
                    idCard();
                } else {
                    console.error('OCR 识别失败:', result);
                }
            },
            error: function(xhr, status, error) {
                console.error('OCR 识别错误:', error);
            }
        });
    }

    function idCard(){
        var documentNumber = $('#documentNumber').val();
        if (documentNumber.length === 18) { // 假设证件号码是18位的身份证号
            var birthDateStr = documentNumber.substring(6, 14); // 提取出生日期部分
            var year = birthDateStr.substring(0, 4);
            var month = birthDateStr.substring(4, 6);
            var day = birthDateStr.substring(6, 8);

            var birthDate = new Date(year, month - 1, day); // 创建日期对象

            if (!isNaN(birthDate.getTime())) { // 检查日期是否有效
                document.getElementById('dateBirth').value = formatBirthDate(birthDate);
                document.getElementById('age').value = calculateAge(birthDate);
            } else {
                document.getElementById('dateBirth').value = '';
                document.getElementById('age').value = '0';
            }
        } else {
            document.getElementById('dateBirth').value = '';
            document.getElementById('age').value = '0';
        }
    }
    // 定义一个函数来计算年龄
    function calculateAge(dateOfBirth) {
        var today = new Date();
        var age = today.getFullYear() - dateOfBirth.getFullYear();
        var m = today.getMonth() - dateOfBirth.getMonth();

        if (today.getFullYear() === dateOfBirth.getFullYear()) {
            return '0';
        }

        if (m < 0 || (m === 0 && today.getDate() < dateOfBirth.getDate())) {
            age--;
        }

        return age;
    }

    // 格式化出生日期
    function formatBirthDate(date) {
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
    }
</script>
<style>
    .modal.inmodal {
        z-index: 1050; /* 确保模态框有一个较高的z-index */
    }

    .select2-dropdown {
        z-index: 9999 !important; /* 强制提高select2下拉菜单的z-index */
    }
    .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: #f3f3f4;
        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; /* 确保文字可见 */
    }


    /* 患者的样式 */
    .ibox2 {
        width: 162px;
        /* height: 370px; */
        overflow: auto;
    }
    .ibox2-title {
        padding: 10px 15px;
        font-size: 16px;
        width: 700px;
    }
    .ibox-content h4 {
        margin-top: 0;
    }
    input[type=file] {
        display: none;
    }
    .modal-content2 {
        width: 800px;
        background-clip: padding-box;
        background-color: #fff;
        border: 1px solid rgba(0, 0, 0, 0);
        border-radius: 4px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.3);
        outline: 0 none;
    }


    .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>




