<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增复购品')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
</head>
<body>
<div class="main-content">

    <div class="form-horizontal">
        <input type="hidden" id="id" name="id" th:value="${id}">
        <div class="customize-form-group">
            <label style="color:olive;font-size: 15px;">复购配置->关联D值品:</label>
            <input name="dValueKey" placeholder="输入D值品名称或D值id查询" class="styled-input" type="text" id="dValueKeyInput">
            <input name="dValueId" placeholder="D值品id" class="styled-input" style="width: 60px;" type="text" readonly id="dValueIdInput">
            <input name="dValueNameInput" placeholder="" class="styled-input" type="text" disabled id="dValueNameInput">
            <button type="button" data-toggle="modal" data-target="#myModal" class="styled-input" style="width: 70px; color: #1E9FFF" id="addDvalueButton111">新增D值</button>
        </div>
        <p class="pull-right">
        <div class="customize-form-group">
            <div class="panel-body">
                <div class="form-group" id="formGroup">
                    <div class="col-sm-12">
                        <div class="col-sm-11" id="carGroup">
                            <!-- 假设这是你的 HTML 结构 -->
                            <div id="iboxContainer">
                                <div class="ibox" id="data-ibox">
                                    <div class="ibox-title">复购药品</div>
                                    <div class="ibox-content">
                                        <table class="table table-bordered" id="drugInfoTable">


                                            <thead>
                                            <tr>
                                                <th>药品编码</th>
                                                <th>药品名</th>
                                                <th>通用名</th>
                                                <th>规格</th>
                                                <th>包装</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>操作 + <a type="button" class="btn btn-xs btn-info"  onclick="selectUsersToParentCallBack2()">添加药品</a></th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            <!-- 数据行将被插入到这里 -->
                                            </tbody>
                                        </table>

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

                    </div>
                </div>
            </div>
        </div>
        </p>
        <div class="center-block ibox-title" >
            <label class="is-required">请选择提交方式：</label>
<!--            th:checked="${dict.dictValue}==${status}"-->
            <div class="input-groups" th:with="type=${@dict.getType('gxhpz_yppz_dzpztjfs')}">
                <input type="radio" class="form-check-radio" th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}"  name="saveStatus" id="saveStatus">
            </div>
        </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">新增D值</h4>
                    </div>
                    <div class="modal-body">
                        <div class="customize-search-form">
                            <div class="customize-form-group edit">
                                <label>D值品id</label>
                                <div class="input-group">
                                    <input type="text" placeholder="系统自动赋值" class="styled-input edit_inputs"  style="width: 350px;height: 50px;" id="dvauleId" name="dvauleid" disabled>
                                </div>
                            </div>
                            <div class="customize-form-group edit">
                                <label>D值品名称</label>
                                <div class="input-group">
                                    <input type="text" placeholder="=商品名&通用名&生产厂家简称" class="styled-input edit_inputs"  style="width: 350px; height: 50px;" id="dname" name="dname">
                                </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" />
<script th:inline="javascript">
    var prefix = ctx + "yppz/drugConfig";
    var prefix_yp = ctx + "dtp/recipe";
    var prefix_dzpz = ctx + "dzpz/dvalueConfig";
    var data;
    var hzparam =[];
    var hzparam2 =[];
    var dvauleid='';
    var dname='';

    // 定义一个函数来更新按钮的可见性
    function updateButtonVisibility() {
        var dValueId = $('#dValueIdInput').val().trim();
        if (dValueId) {
            $('#addDvalueButton').hide();
        } else {
            $('#addDvalueButton').show();
        }
    }
    $(document).ready(function() {
        // 假设pageData中有drugCode, productName等属性
        var drugCode = /*[[${drugCode}]]*/ '';
        var productName = /*[[${productName}]]*/ '';

        console.log("Drug Code: " + drugCode);
        console.log("Product Name: " + productName);

        // 使用Thymeleaf的语法来获取后端传来的值
        var drugData = /*[[${drugData}]]*/ {};
if(drugData != null || drugData != undefined){
    console.log("data===" + JSON.stringify(drugData));
    var tableBody = $('#drugInfoTable tbody');
    var row = `
            <tr data-product-id="` + drugData.id + `">
                <td>` + drugData.mdmCode + `</td>
                <td>` + drugData.productName + `</td>
                <td>` + drugData.genericName + `</td>
                <td>` + drugData.specification + `</td>
                <td>` + drugData.packaging + `</td>
                <td>` + drugData.manufacturerShortName + `</td>

                <td class="hidden-column">` + drugData.isFollowUpManaged + `</td>
                <td class="hidden-column">` + drugData.isColdChainManaged + `</td>
                <td class="hidden-column">` + drugData.isRegisteredManaged + `</td>
                <td class="hidden-column">` + drugData.isCharityAidManaged + `</td>
                <td class="hidden-column">` + drugData.administrationMethod + `</td>
                <td class="hidden-column">` + drugData.indicationDescription + `</td>
                <td class="hidden-column">` + drugData.dosageAndAdministration + `</td>
                <td><button onclick="deleteRow('` + drugData.id + `')" class="btn btn-danger">删除</button></td>
             </tr>`;

    tableBody.append(row);
}

        let timeout;

        // 监听 dValueKey 输入框的 input 事件
        $('#dValueKeyInput').on('input', function() {
            clearTimeout(timeout);
            var query = $('#dValueKeyInput').val().trim();
            // 如果输入为空，清空 dValueId 输入框并停止进一步操作
            if (!query) {
                $('#dValueIdInput').val('');
                $('#dValueName').val('');

                updateButtonVisibility(); // 更新按钮可见性
                return;
            }

            // 使用防抖机制延迟发送请求
            timeout = setTimeout(() => {
                // 发送 AJAX 请求到服务器查询数据
                hzparam={query:query};//模拟微信扫码获取微信openId
                console.log("hzparam===="+hzparam);
                var tableBody = $('#drugInfoTable tbody');
                // 清空表格中的所有数据行
               // $('#drugInfoTable tbody').empty();
                $.ajax({
                    cache: true,
                    type: "POST",
                    url: prefix_dzpz+'/searchDvalue', // 替换为实际的搜索 URL
                    data: hzparam,
                    async: false,
                    success: function (data) {
                        console.log("data===="+data);
                        if(data.code==0){

                            // 如果找到匹配的数据，更新 dValueId 输入框
                            $('#dValueIdInput').val(data.data.d_value_code);
                            $('#dValueKeyInput').val(data.data.d_value_code);
                            $('#dValueNameInput').val(data.data.dValueName);

                            updateButtonVisibility(); // 更新按钮可见性
            //                 var row = `
            //     <tr data-product-id="${data.data.id}">
            //         <td>${data.data.mdmCode}</td>
            //         <td>${data.data.productName}</td>
            //         <td>${data.data.genericName}</td>
            //         <td>${data.data.specification}</td>
            //          <td>${data.data.packaging}</td>
            //         <td>${data.data.manufacturerShortName}</td>
            //          <td class="hidden-column">${data.isFollowUpManaged}</td>
            //         <td class="hidden-column">${data.isColdChainManaged}</td>
            //         <td class="hidden-column">${data.isRegisteredManaged}</td>
            //         <td class="hidden-column">${data.isCharityAidManaged}</td>
            //         <td class="hidden-column">${data.administrationMethod}</td>
            //         <td class="hidden-column">${data.indicationDescription}</td>
            //         <td class="hidden-column">${data.dosageAndAdministration}</td>
            //         <td><button onclick="deleteRow('${data.data.id}')" class="btn btn-danger">删除</button></td>
            //     </tr>
            // `;
            //                 tableBody.append(row);
                        }else{
                            // 清空表格中的所有数据行
                           // $('#drugInfoTable tbody').empty();
                            // 如果没有找到匹配的数据，清空 dValueId 输入框
                            $('#dValueIdInput').val('');
                            updateButtonVisibility(); // 更新按钮可见性
                        }

                    },
                    error: function(error) {
                        // 清空 dValueId 输入框
                        $('#dValueIdInput').val('');
                    }
                });

            }, 360); // 300ms 的延迟
        });
        // 页面加载时检查 dValueIdInput 的初始状态
        updateButtonVisibility();
    });

    function submitHandler() {
        submitDrugInfo();
    }
    // callBack获取父窗口方法（方式二） $('#myModal').modal('show');  $('#myModal').modal('hide');  $.modal.close(); openId = document.getElementById('openId').value;
    function selectUsersToParentCallBack2(){
        var options = {
            title: '添加维护D值品',
            width: 1000,
            height: 600,
            url: prefix + '/allDrugsInfo',
            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) {
            // 检查是否已经存在该药品
            if (!isProductExist(item.productId)) {
                // 向表格中添加一行
                var row = `
                <tr data-product-id="${item.productId}">
                    <td>${item.mdmCode}</td>
                    <td>${item.productName}</td>
                    <td>${item.genericName}</td>
                    <td>${item.specification}</td>
                     <td>${item.packaging}</td>
                    <td>${item.manufacturerShortName}</td>
                    <td class="hidden-column">${item.isFollowUpManaged}</td>
                    <td class="hidden-column">${item.isColdChainManaged}</td>
                    <td class="hidden-column">${item.isRegisteredManaged}</td>
                    <td class="hidden-column">${item.isCharityAidManaged}</td>
                    <td class="hidden-column">${item.administrationMethod}</td>
                    <td class="hidden-column">${item.indicationDescription}</td>
                    <td class="hidden-column">${item.dosageAndAdministration}</td>

                    <td><button onclick="deleteRow('${item.productId}')" class="btn btn-danger">删除</button></td>
                </tr>
            `;

                tableBody.append(row);
            } else {
                $.modal.alertWarning(`药品 ${item.productName} 已经添加了`);
            }
        });

        $.modal.close(index);
    }

    function deleteRow(productId) {
        // 删除对应行
        $('#drugInfoTable tbody tr[data-product-id="' + productId + '"]').remove();
    }

    function isProductExist(productId) {
        // 检查表格中是否已经存在该药品
        return $('#drugInfoTable tbody tr[data-product-id="' + productId + '"]').length > 0;
    }
    function getSelectedSaveStatus() {
        return $('input[name="saveStatus"]:checked').val();
    }
    function getTableData() {
        var tableRows = [];
        $('#drugInfoTable tbody tr').each(function(index, row) {
            var rowData = {
                mdmCode: $(row).find('td:eq(0)').text().trim(),
                productName: $(row).find('td:eq(1)').text().trim(),
                genericName: $(row).find('td:eq(2)').text().trim(),
                specification: $(row).find('td:eq(3)').text().trim(),
                packaging: $(row).find('td:eq(4)').text().trim(),
                manufacturerShortName: $(row).find('td:eq(5)').text().trim(),
                // 隐藏列的数据可以从data-*属性中获取
                isFollowUpManaged: $(row).data('is-follow-up-managed'),
                isColdChainManaged: $(row).data('is-cold-chain-managed'),
                isRegisteredManaged: $(row).data('is-registered-managed'),
                isCharityAidManaged: $(row).data('is-charity-aid-managed'),
                administrationMethod: $(row).data('administration-method'),
                indicationDescription: $(row).data('indication-description'),
                dosageAndAdministration: $(row).data('dosage-and-administration'),
                productId: $(row).data('product-id')
            };
            tableRows.push(rowData);
        });
        return tableRows;
    }
    function submitDrugInfo() {
        debugger
       // $('#dValueIdInput').val('');
        var dValueId = $('#dValueIdInput').val().trim();
        var dValueName = $('#dValueNameInput').val().trim();
        if (!dValueId) {
            $.modal.alertWarning("请输入有效的D值id");
            return;
        }
        var flag = false;
       var saveStatus = getSelectedSaveStatus();
        console.log("saveStatus===="+saveStatus);
        if(saveStatus =='' || saveStatus ==undefined){
            $.modal.alertWarning("请选择提交方式");
            return false;
        }
        var saveStatusIn=null;
        if(saveStatus=="保存"){
            saveStatusIn=0;
        }
        if(saveStatus=="保存并启用"){
            saveStatusIn= 1;
        }
        // 创建一个 FormData 对象用于提交表单数据
        var formData = new FormData();
        formData.append('saveStatus', saveStatusIn);
        formData.append('dValueId', dValueId);
        formData.append('dValueName', dValueName);
        formData.append('type', '1');//标记为关联配置操作
        // 将药物数据序列化为 JSON 字符串并添加到 FormData 中

        formData.append('drugData', JSON.stringify(getTableData()));

        // 发送 AJAX 请求或构建表单进行提交
        $.ajax({
            url: prefix + "/editDrugConfig",
            method: 'POST',
            data: formData,
            processData: false,  // 不处理数据，因为 data 已经是字符串
            contentType: false,  // 不设置内容类型，让浏览器自动设置
            success: function(response) {
                console.log('提交成功ok:', response);
                $.modal.msgSuccess(response.msg);
                $.modal.close();
                $.operate.successCallback(response);
                // 处理成功响应...
            },
            error: function(error) {
                $.modal.alertError("失败");
                console.error('提交失败:', error);
                // 处理错误响应...
            }
        });
    }
    function saveRow() {
        // 获取表单数据 form-relation-add relationTable 联系人电话 lxrdh 联系人姓名 lxrxm 联系人关系 lxrgx
        dname = document.getElementById('dname').value;
        //dvauleid = document.getElementById('dvauleid').value;
        // 检查数据是否为空
        if (!dname) {
            $.modal.alert('请填写D值名称');
            return;
        }
        hzparam2={nameValue:dname};
        console.log("hzparam========"+hzparam)
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix_dzpz + "/createDVauleId",
            data: hzparam2,
            async: false,
            success: function (data) {
                if(data.code==0){
                    dvauleid = data.data.dvauleid;
                    // 如果找到匹配的数据，更新 dValueId 输入框
                    $('#dValueIdInput').val(data.data.dvauleid);
                    $('#dValueKeyInput').val(data.data.dValueName);
                    $('#dValueNameInput').val(data.data.dValueName);
                    flag = true;
                    // 关闭模态框
                    $('#myModal').modal('hide');
                    //$.modal.close();
                }else{
                    $('#dValueIdInput').val("");
                    $('#dValueKeyInput').val("");
                    $('#dValueNameInput').val("");
                    $.modal.alertError(data.msg);
                }

            } ,error: function (request) {
                $.modal.alertError("提交失败");
            },
        });

    }

</script>
<style>
    .center-block {
        display: block;
        margin-left: auto;
        margin-right: auto;
        width: fit-content;
    }
    .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;
    }
    .ibox-content {
        padding: 15px;
    }
    .ibox-content h4 {
        margin-top: 0;
    }
    .customize-form-group2 {
        display: inline-block;
    }
    .styled-input2 {
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 4px;
        width: 200px;
    }
    .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: -1px;
    }
    /* 添加一些基础样式 */
    body {
        font-family: Arial, sans-serif;
    }
    table {
        width: 400px;
        border-collapse: collapse;
    }
    th, td {
        text-align: left;
        padding: 8px;
        border-bottom: 1px solid #ddd;
    }
    tr:nth-child(even) {
        width: 15px;
        background-color: #f2f2f2;
    }
    .hidden-column {
        display: none;
    }
</style>
</body>
</html>




