<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
    <th:block th:include="include :: header('新增处方')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
</head>
<body>
<div class="main-content">
    <form id="form-prescription-add" class="form-horizontal">
<!--        <div class="ibox float-e-margins">-->
<!--            <label class="font-noraml">处方上传</label>-->
<!--            <div class="new-contentarea tc">-->
<!--                <a href="javascript:void(0)" class="upload-img"><label for="inputImage">上传图像</label></a>-->
<!--                <input type="file" name="avatar" id="inputImage" onchange="uploadImage(this)" accept="image/*"/>-->

<!--            </div>-->
<!--        </div>-->
<!--        <div class="ibox">-->
<!--            <div class="ibox-title">-->
<!--                <img id="uploadedImage" src="" alt="上传的图片" style="max-width: 100%; display: block;">-->
<!--            </div>-->
<!--        </div>-->
                    <ul class="list-group list-group-striped">
                        <li class="list-group-item hidden"  id="prescriptionNumberItem"><i class="fa fa-user"></i>
                            <input type="hidden" name="prescriptionImg" id="prescriptionImg" value="">
                            <b  class="font-noraml">处方单号：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <input id="prescriptionNumber" name="prescriptionNumber" placeholder="请输入处方单号" class="styled-input" type="text">
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item hidden"  id="prescriptionSourceItem"><i class="fa fa-user"></i>
                            <b  class="font-noraml">处方来源：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <input id="prescriptionSource" name="prescriptionSource" placeholder="处方来源" class="styled-input" type="text">
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item"><i class="fa fa-envelope-o"></i>
                            <b class="font-noraml">处方日期：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                            <input name="prescriptionDate" placeholder="处方日期"  id="prescriptionDate" class="time-input time-input2" type="text">
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item"><i class="fa fa-user"></i>
                            <b  class="font-noraml">医院：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <select name="hospital" class="styled-input" th:with="type=${@dict.getType('sys_select_dtp_hospital')}">
                                <option value="">请选择</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}" >
                                </option>
                            </select>
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item"><i class="fa fa-user"></i>
                            <b  class="font-noraml">处方医生：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <input id="doctor" name="doctor" placeholder="请输入医生" class="styled-input" type="text" maxlength="30" >
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item"><i class="fa fa-envelope-o"></i>
                            <b  class="font-noraml">科室：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <input id="department" name="department" placeholder="请输入科室" class="form-control" type="text" maxlength="50">
                            </div>
                            </p>
                        </li>
                        <li class="list-group-item">
                            <i class="fa fa-envelope-o"></i>
                            <b class="font-noraml">疾病类型：<i style="color: #307cc2;">可多选或直接输入疾病名称搜索</i></b>
                            <p class="pull-right">
                            <div class="form-group2">
                                <label for="category-select">疾病类型：</label>
                                <select id="category-select" style="width: 100%"  class="form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                                    <option value="">请选择疾病大类</option>
                                </select>
                            </div>
                            <div class="form-group2">
                                <label for="subcategory-select">小类：</label>
                                <select id="subcategory-select" style="width: 100%" class="form-control select2-multiple" multiple placeholder="请选择或输入搜索">
                                    <option value="">请选择子类别</option>
                                </select>
                            </div>

                            </p>
                        </li>

                        <li class="list-group-item"><i class="fa fa-envelope-o"></i>
                            <b  class="font-noraml">临床诊断：</b>
                            <p class="pull-right">
                            <div class="customize-form-group select-time">
                                <select name="clinicalDiagnosis" class="styled-input" th:with="type=${@dict.getType('sys_select_dtp_ysfw_lczd')}"  >
                                <option value="">请选择</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}">
                                </option>
                                </select>
                            </div>
                            </p>
                        </li>
                    </ul>
    </form>
    <div class="form-horizontal">
        <h4 class="form-header h4">药品信息</h4>
        <p class="pull-right">
        <div class="customize-form-group select-time">
            <div class="panel-body">
                <strong>药品信息</strong>
                <div class="form-group" id="formGroup">
                    <div class="col-sm-12">
                        <div class="col-sm-11" id="carGroup">
                            <div id="iboxContainer">
                                <ul class="list-group list-group-striped" id="inputList">
                                    <!-- 输入框将在这里动态添加 -->
                                </ul>
                            </div>
                        </div>
                        <div class="col-sm-offset-5 col-sm-10">
                            <button type="button"  onclick="selectUsersToParentCallBack2()" class="btn btn-w-m btn-primary">添加药品</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        </p>
        <div class="customize-form-group" style="justify-content: center;">
        <button type="button"  onclick="bangding()" class="btn btn-w-m btn-success">绑定患者</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-relation-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>
                        <h4 class="modal-title">微信绑定</h4>
                    </div>
                    <div class="modal-body">
                        <div class="customize-search-form">
                            <div class="customize-form-group edit">
                                <label>微信绑定</label>
                                <div class="input-group">
                                    <input type="text" placeholder="请输入openId" class="styled-input edit_inputs"  style="width: 200px;" id="openId" name="openId">
                                </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="saveRow()">绑定保存</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: bootstrap-fileinput-js" />

<th:block th:include="include :: bootstrap-suggest-js" />
<th:block th:include="include :: bootstrap-typeahead-js" />
<script>
    var prefix = ctx + "dtp/recipe";
    var prefix_bd = ctx + "dtp/recipe";
    var jbtype='';
    var saveData;
    var hzparam =[];
    var openId='';
    var data;

    /* 读取 疾病大类 和小类 数据*/
    $(document).ready(function() {
        var clearSpan = $('.select2-selection-clear');
        // 初始化 Select2 插件
        $('#category-select').select2({
            placeholder: "请选择或直接输入搜索",
            //allowClear: true //在输入框最后 有一个 删除所有的X 但是会出现 第一个删除出现问题有空格
        });
        // Listen for the 'select2:select' event
        $('#category-select').on('select2:select', function(e) {
            var clearSpan = $('.select2-selection-clear');
            if (clearSpan.length > 0) {
                clearSpan.remove();
            }
        });

        // 发送 AJAX 请求获取疾病大类数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate',
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var options = $('#category-select');
                // 清空已有选项（除了第一个默认选项）
                options.find('option').not(':first').remove();
                $('<option>', {
                    value: '',
                    text : '请选择疾病类型'
                }).appendTo(options);
                // 遍历返回的数据并添加选项
                $.each(data.value, function(index, item) {
                    $('<option>', {
                        value: item.id,
                        text : item.categoryName
                    }).appendTo(options);
                });

                // 重新初始化 Select2 以反映新的选项
                options.trigger('change');
            },
            error: function(xhr, status, error) {
                console.error("Failed to load disease categories:", error);
            }
        });

        // 初始化子类别下拉框
        $('#subcategory-select').select2({
            placeholder: "请选择或直接输入搜索",
            //allowClear: true
        });

        // 监听第一个下拉框的选择事件
        $('#category-select').on('change', function() {
            var selectedCategory = $(this).val();
            if (selectedCategory.length > 0) {
                loadSubcategories(selectedCategory);
            } else {
                // 如果没有选择任何项，清空子类别下拉框
                $('#subcategory-select').find('option').not(':first').remove();
                $('#subcategory-select').trigger('change');
            }
        });
    });

    function loadSubcategories(categoryId) {
        // 模拟从服务器获取子类别数据
        $.ajax({
            url: ctx + 'sp/sp/typeDate2?jbtype=' + categoryId, // 假设 ctx 是你的上下文路径
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                var options = $('#subcategory-select');
                // 清空已有选项（除了第一个默认选项）
                options.find('option').not(':first').remove();

                // 遍历返回的数据并添加选项
                $.each(data.value, function(index, item) {
                    $('<option>', {
                        value: item.ida,
                        text : item.categoryNamea
                    }).appendTo(options);
                });

                // 重新初始化 Select2 以反映新的选项
                options.trigger('change');
            },
            error: function(xhr, status, error) {
                console.error("Failed to load subcategories:", error);
            }
        });
    }

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

    // document.getElementById('diseaseType').addEventListener('change', function() {
    //     jbtype = this.value;
    //         if(jbtype=='慢病'){
    //             specificDiseaseDiv1
    //             $('#specificDiseaseDiv1').show();
    //             $('#specificDiseaseDiv2').hide();
    //             $('#specificDisease2').prop('selectedIndex', 0);
    //         }else if(jbtype=='肿瘤'){
    //             $('#specificDiseaseDiv2').show();
    //             $('#specificDiseaseDiv1').hide();
    //             $('#specificDisease1').prop('selectedIndex', 0);
    //         }else{
    //             $('#specificDisease1').prop('selectedIndex', 0);
    //             $('#specificDisease2').prop('selectedIndex', 0);
    //             $('#specificDiseaseDiv2').hide();
    //             $('#specificDiseaseDiv1').hide();
    //         }
    //     console.log('Selected value:', this.value);
    // });
    function submitHandler() {
            add();
    }
    function add() {
        //$('#prescriptionSourceItem').hide();//控制是第三方存入后 登记处方时的信息显示字段
        //$('#prescriptionNumberItem').hide();//控制是第三方存入后 登记处方时的信息显示字段
        var formData = [];
        var flag = false;
        // 获取选中的值
        var JBDLval = $('#category-select').val(); // 疾病大类
        var JBXLval = $('#subcategory-select').val(); // 疾病小类
        // 获取选中的选项对象集合
        var selectedOptionsDL = $('#category-select option:selected');
        var selectedOptionsXL = $('#subcategory-select option:selected');

        // 使用 .map() 来创建一个包含选中选项文本的数组
        var JBDL = selectedOptionsDL.map(function() { // 疾病大类
            return $(this).text();
        }).get(); // 获取的数据格式 [ "肿瘤治疗并发症与合并症名称", "风湿免疫疾病名称库" ]
        var JBXL = selectedOptionsXL.map(function() { // 疾病小类
            return $(this).text();
        }).get(); // 获取的数据格式 [ "肿瘤治疗并发症与合并症名称", "风湿免疫疾病名称库" ]

        // 同样地，如果你需要获取选中的 ID 和名称，可以这样做：
//         var selectedData = selectedOptions.map(function() {
//             return {
//                 id: $(this).val(),
//                 name: $(this).text()
//             };
//         }).get();  // 获取的数据格式 [{ id: "2", name: "肿瘤治疗并发症与合并症名称" }, { id: "3", name: "风湿免疫疾病名称库" }]


            return;
        $('.ibox').each(function() {
            var productId = $(this).find('input[name="productId"]').val();
            var mdmCode = $(this).find('input[name="mdmCode"]').val();
            var isFlipItem = $(this).find('input[name="isFlipItem"]').val();
            var specification = $(this).find('input[name="specification"]').val();
            var genericName = $(this).find('input[name="genericName"]').val();
            var productName = $(this).find('input[name="productName"]').val();
            var quantity = $(this).find('input[name="quantity"]').val();
            var usageMethod = $(this).find('select[name="usageMethod"]').val();
            var frequency = $(this).find('select[name="frequency"]').val();
            var wordUsage = $(this).find('input[name="wordUsage"]').val();
            var medicationCycle = $(this).find('input[name="medicationCycle"]').val();
            if (productId && quantity && usageMethod && frequency && wordUsage && medicationCycle && productName && genericName && mdmCode && isFlipItem && specification ) {
                formData.push({
                    productId: productId,
                    mdmCode: mdmCode,
                    quantity: quantity,
                    genericName: genericName,
                    isFlipItem: isFlipItem,
                    specification: specification,
                    productName: productName,
                    usageMethod: usageMethod,
                    frequency: frequency,
                    wordUsage: wordUsage,
                    medicationCycle: medicationCycle
                });
            }
            if(isFlipItem==="是"){
                flag = true;
            }
        });
        if ($.validate.form()) {
             data = $("#form-prescription-add").serializeArray();
            data.push({name:'drugList',value:JSON.stringify(formData)});
            data.push.apply(data,hzparam);
            console.log("hzparam"+hzparam)

        }

            debugger
            log.info(data);
            $.ajax({
                cache: true,
                type: "POST",
                url: ctx + "dtp/recipe/SaveRecipe",
                data: data,
                async: false,
                error: function (request) {
                    $.modal.alertError("系统错误");
                },
                success: function (data) {
                    debugger
                        if(flag){
                            $('#myModal').modal('show');
                        }else{
                            $.modal.alertSuccess("新增成功");
                            $.modal.close();
                        }
                }
            });
    }
    function saveRow() {
        // 获取表单数据 form-relation-add relationTable 联系人电话 lxrdh 联系人姓名 lxrxm 联系人关系 lxrgx
           openId = document.getElementById('openId').value;
        // 检查数据是否为空
        if (!openId) {
            $.modal.alert('请填写openId');
            return;
        }
        hzparam.push({name:"openId",value:openId});//模拟微信扫码获取微信openId
        $.ajax({
            cache: true,
            type: "POST",
            url: ctx + "dtp/pmService/ShaoMaShangFan",
            data: hzparam,
            async: false,
            error: function (request) {
                $.modal.alertError("系统错误");
            },
            success: function (data) {
                if(data.code==0){
                    $.modal.alertSuccess("新增并上翻成功");
                    flag = false;
                    // 关闭模态框
                    $('#myModal').modal('hide');
                    $.modal.close();
                }else{
                    $.modal.alertError(data.msg);
                }

            }
        });

    }

    function bangding(){
        huanzheBanding();
    }
    function huanzheBanding(data){
        var options = {
            title: '患者绑定',
            url: prefix + "/huanzheBanding",
            width:1000,
            callBack: doSubmithz
        };
        $.modal.openOptions(options);
    }

    function doSubmithz(index, layero){
        debugger
    var rows = layero.find("iframe")[0].contentWindow.selectTableObject();
    if (rows.length == 0) {
        $.modal.alertWarning("请至少选择一条记录");
        return;
    }

      var id = rows[0].id[0];
      var name= rows[0].name[0];
      var phoneNumber=  rows[0].phoneNumber[0];
      var documentNumber=  rows[0].documentNumber[0];
      var gender=  rows[0].gender[0];
      var age=  rows[0].age[0];
        $.modal.close(index);
        hzparam.push({name:"patientId",value:id},{name:"patientName",value:name},{name:"patientPhone",value:phoneNumber},{name:"documentNumber",value:documentNumber},{name:"gender",value:gender},{name:"age",value:age});
        console.log("hzparam="+hzparam)
    }

    // callBack获取父窗口方法（方式二）
    function selectUsersToParentCallBack2(){
        var options = {
            title: '药品信息',
            url: prefix + "/drugInfo",
            callBack: doSubmit2
        };
        $.modal.openOptions(options);
    }
    function doSubmit2(index, layero){
        var rows = layero.find("iframe")[0].contentWindow.selectTableObject();
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        rows.forEach(function(item, index) {
            // 生成 ibox 容器
            var ibox = `<div class="ibox" id="ibox-${item.productId[0]}">
                <div class="ibox-title">
                    <h5>${item.mdmCode[0]} - ${item.productName[0]}</h5>
                    <!-- ... 其他隐藏输入字段 ... -->
                </div>
                <div class="ibox-content">
                    <table class="table table-bordered">
                        <tbody>
                            <tr><td>通用名</td><td>${item.genericName[0]}</td></tr>
                            <tr><td>规格</td><td>${item.specification[0]}</td></tr>
                        </tbody>
                    </table>
                    <div class="form-group row">
                        <label class="col-sm-1">数量</label>
                        <div class="col-sm-2"><input name="quantity" placeholder="数量" id="quantity-${item.productId[0]}" class="styled-input3" type="number"></div>
                        <label class="col-sm-1">单次用量</label>
                        <div class="col-sm-2"><input name="wordUsage" placeholder="单次用量" id="wordUsage-${item.productId[0]}" class="styled-input4" type="text"></div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-1">使用频次</label>
                        <div class="col-sm-2"><select name="frequency" id="frequency-${item.productId[0]}" class="styled-input4"><option value="">请选择</option><option value="每日一次">每日一次</option><option value="每日两次">每日两次</option></select></div>
                        <label class="col-sm-1">用法</label>
                        <div class="col-sm-2"><select name="usageMethod" id="usageMethod-${item.productId[0]}" class="styled-input3"><option value="">请选择</option><option value="口服">口服</option><option value="注射">注射</option></select></div>
                    </div>
                    <div class="form-group row">
                        <label class="col-sm-1">用药周期(天)</label>
                        <div class="col-sm-2"><input name="medicationCycle" placeholder="用药周期" id="medicationCycle-${item.productId[0]}" class="styled-input4" type="text"></div>
                        <div class="col-sm-7 text-right">
                            <button onclick="deleteRow('${item.productId[0]}')" class="btn btn-danger btn-sm">删除</button>
                        </div>
                    </div>
                </div>
            </div>`;

            // 添加到容器
            $('#iboxContainer').append(ibox);
        });
        $.modal.close(index);
    }
    function deleteRow(productId) {
        // 删除 ibox 容器
        $('#ibox-' + productId).remove();

        // 更新 productId 显示
        $('#productId').html('');
    }

    /* 用户管理-新增-选择门店树 */
    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);
    }



</script>
<style>
    .hidden {
        display: none;
    }
    .ibox {
        width: 680px;
        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;
    }
    .ibox-content {
        padding: 15px;
    }
    .ibox-content h4 {
        margin-top: 0;
    }
    .styled-input3 {
        display: inline-block;
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 4px;
        width: 100px;
    }
    .styled-input4 {
        display: inline-block;
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 4px;
        width: 100px;
    }
    /*.col-sm-6 {
        width: 125%;
    }*/
    /*.form-horizontal .form-group {
        margin-right: 384px;
        margin-left: 3px;
    }*/
    input[type=file] {
        display: none;
    }
    .form-group {
        margin-bottom:5px;
    }
    /* 添加一些基础样式 */
    body {
        font-family: Arial, sans-serif;
    }
    /*.ibox-content .table {
        width: 400px;
        border-collapse: collapse;
    }*/
    .ibox-content.table th, td {
        text-align: left;
        padding: 8px;
        border-bottom: 1px solid #ddd;
    }
    .ibox-content.table tbody tr:nth-child(even) {
        width: 15px;
        background-color: #f2f2f2;
    }
</style>
</body>
</html>




