<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('随访SOP新增')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: layout-latest-css" />
</head>
<body>
<div class="ui-layout-center">
    <div class="col-sm-12">
        <div class="float-e-margins">
            <div class="ibox-title">
                <h5>随访SOP</h5>
            </div>
            <div class="ibox-content">
            <form id="form-SDtpYypzFollowUpSop-edit">
                    <div class="customize-form-group-row">
                        <label class="control-label is-required">SOP名称：</label>
                        <input name="templateName" id="templateName" placeholder="请输入SOP名称" class="styled-input input-field" type="text"  required>
                    </div>
                        <div class="customize-form-group-row">
                            <label class="control-label is-required">&nbsp;业务归属:&nbsp;&nbsp;</label>
                            <select name="businessBelonging" id="businessBelonging" class="styled-input input-field"   th:with="type=${@dict.getType('sys_select_dtp_ywgs')}">
                                <option disabled selected>请选择业务归属</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictLabel}"></option>
                            </select>
                        </div>
            </form>
            <form id="form-syyp-durg">
                        <div class="ibox" id="data-ibox" style="overflow: auto;">
                            <div class="ibox-title" style="width: 100%;">适用药品:已选择 <span id="drug-count">0</span> 种药品</div>
                            <table class="fixed-layout-table table1" id="drugInfoTable">
                                <thead>
                                <tr>
                                    <th>操作+<a type="button" class="btn btn-primary btn-sm" onclick="selectUsersToParentCallBack2()">添加药品</a></th>
                                    <th>药品编码</th>
                                    <th>药品名</th>
                                    <th>规格</th>
                                </tr>
                                </thead>
                                <tbody>
                                <!-- 数据行将被插入到这里 -->
                                </tbody>
                            </table>
                        </div>
             </form>
                <form id="form-jdpz-nodes" >
                    <div class="customize-form-group-row">
                        <label class="control-label is-required">节点配置：</label>
                        <div class="col-sm-6">
                            <div class="tabs-container">
                                <button type="button"  onclick="addNode()" class="btn btn-outline btn-primary">新增节点</button>
                                <ul class="nav nav-tabs" id="addNodeSelect">
                                    <!--动态添加表单数据-->
                                </ul>
                                <div class="tab-content" id="addNode">
                                    <!--动态添加表单数据-->
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </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-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>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<th:block th:include="include :: select2-js" />
<th:block th:include="include :: bootstrap-table-fixed-columns-js" />
<th:block th:include="include :: layout-latest-js" />
</body>
</html>
<script>
    var prefix = ctx + "dtp/recipe";
    var prefix_yppz= ctx + "yppz/drugConfig";
    var count = 0;
    let carNum=1;//选项卡id
    var index=0;
    // 存储已添加的过滤条件数量
    var selectedOption = []; // 这里存储当前选中的选项
    var selectCount=0;
    var applicableDrug=[];
    // 页面加载时初始化药品数量
    $(document).ready(function() {
        updateDrugCount(); // 初始化药品数量
        // 绑定删除按钮点击事件
        $(document).on('click', '.delete-drug-btn', function(event) {
            event.preventDefault(); // 阻止默认行为
            var productId = $(this).data('product-id');
            deleteRow(productId);
        });
    });

    function submitHandler() {
        var businessBelonging=$("#businessBelonging").val();
        var templateName=$("#templateName").val();
        if(templateName=="" || templateName==undefined){
            $.modal.alertWarning("请输入SOP名称");
            return;
        }
        if(businessBelonging=="" || businessBelonging==undefined){
            $.modal.alertWarning("请选择业务归属");
            return;
        }
        applicableDrug=  getTableData();
        if(applicableDrug.length==0){
            $.modal.alertWarning("请添加药品");
            return;
        }
        var prefix = ctx + "dtp/sdtpyypzfollowupsop";
        var data = $("#form-SDtpYypzFollowUpSop-edit").serializeArray();
        data.push({name:"nodesData",value:JSON.stringify(collectNodesData())});
        data.push({name:"applicableDrug",value:JSON.stringify(applicableDrug)});
        console.log("data="+data)
        $.operate.saveTab(prefix + "/sDtpYypzFollowUpSopAdd", data);
    }


    function collectNodesData() {
        // 获取所有节点
        const nodes = document.querySelectorAll('.tabs-container .tab-pane');
        // 创建一个空数组来保存所有节点的数据
        const nodesData = [];

        // 遍历每个节点
        nodes.forEach(node => {
            // 创建一个空对象来保存当前节点的数据
            const nodeData = {};
            var nodeIdStr=node.id;
            var nodeId=  nodeIdStr.substring(4);
            console.log("nodeId="+nodeId);
            // 获取节点内的所有输入字段
            const inputs = node.querySelectorAll('input, select');

            // 遍历每个输入字段并收集其值
            inputs.forEach(input => {
                // 忽略没有 name 属性的字段
                if (!input.name) {
                    return;
                }
                // 对于复选框和单选按钮，只收集选中的值
                if (input.type === 'checkbox' || input.type === 'radio') {
                    if (!input.checked) {
                        return;
                    }
                }
                // 将值添加到当前节点的数据对象中
                nodeData[input.name] = input.value;
            });
            // 将当前节点的数据对象添加到数组中
            nodeData.filtersData=  collectFiltersData(nodeId);
            nodesData.push(nodeData);
        });
        // 返回所有节点的数据
        return nodesData;
    }
    function collectFiltersData(nodeId) {
           var filtersContainer = document.getElementById('filtersContainer'+nodeId);
             if(filtersContainer){
                 // 获取所有过滤条件行
                 var filterRows = filtersContainer.getElementsByClassName('filter-row');
                 // 创建一个数组来存储所有行的数据
                 var allFilterData = [];
                 // 遍历每一行
                 Array.from(filterRows).forEach(function(filterRow, rowIndex) {
                     // 获取每一行内各个选择器的值
                     var traits = filterRow.querySelector('[name^="trait"]');
                     var traitValue = filterRow.querySelector('[name^="traitValue"]');
                     var judgingCondition = filterRow.querySelector('[name^="judgingCondition"]');
                     var judgmentSelectValue = filterRow.querySelector('[name^="judgmentSelectValue"]');
                     var judgmentInputValue =filterRow.querySelector('[name^="judgmentInputValue"]');
                     // 创建一个对象来存储这一行的数据
                     var rowFilterData = {};
                     if (traits) {
                         rowFilterData['traits'] = traits.value;
                     }
                     if (traitValue) {
                         rowFilterData['traitValue'] = traitValue.value;
                     }
                     if (judgingCondition) {
                         rowFilterData['judgingCondition'] = judgingCondition.value;
                     }
                     if (judgmentSelectValue) {
                         rowFilterData['judgmentValue'] = judgmentSelectValue.value;
                     }

                     if (judgmentInputValue) {
                         rowFilterData['judgmentValue'] = judgmentInputValue.value;
                     }
                     // 添加一个属性来标识这一行的位置
                     rowFilterData['rowIndex'] = rowIndex + 1; // 行号从 1 开始
                     // 创建一个对象来存储这一行的数据
                     var filterData = {
                         traits: traits,
                         traitValue: traitValue,
                         judgingCondition: judgingCondition,
                         judgmentValue: judgmentSelectValue,
                         judgmentValueInput: judgmentInputValue
                     };

                     // 将这一行的数据添加到总数据数组中
                     allFilterData.push(rowFilterData);
                 });
                 // 将总数据数组转换为 JSON 字符串
                 return allFilterData;
             } else {
                 return null;
             }
    }
    function selectUsersToParentCallBack2(){
        var options = {
            title: 'SOP随访药品配置',
            width: 1000,
            height: 600,
            url: prefix_yppz + '/getAllProduct',
            callBack: doSubmit2
        };
        $.modal.openOptions(options);
    }
    function  toTask(){
        selectCount++;
        // 使用 includes 方法检查 carNum 是否已在 carNumFlag2 数组中
        // 创建并设置 div 的内容
        var filtersContainer = document.getElementById('filtersContainer'+carNum);
        var filterRow = document.createElement('div');
        filterRow.className = 'filter-row';

        // 创建并初始化一级下拉列表 特征
        var levelOneSelect = document.createElement('select');
        levelOneSelect.id = 'level-one'+selectCount;
        levelOneSelect.name = 'trait';
        levelOneSelect.className = 'styled-input';
        levelOneSelect.innerHTML = `
        <option value="" disabled selected>请选择一级分类</option>
        <option value="patient-feature">患者特征</option>
        <option value="patient-did-feature">患者Did特征</option>
    `;
        filterRow.appendChild(levelOneSelect);
        // 创建二级、三级、四级的容器和相关元素，但初始时不显示它们 特征值
        var levelTwoContainer = document.createElement('div');
        levelTwoContainer.id = 'level-two-container'+selectCount;
        levelTwoContainer.className = 'styled-input';
        // 创建并初始化二级下拉列表
        var levelTwoSelect = document.createElement('select');
        levelTwoSelect.id = 'level-two'+selectCount;
        levelTwoSelect.name = 'traitValue';
        levelTwoSelect.className = 'styled-input';
        levelTwoContainer.style.display = 'none';
        filterRow.appendChild(levelTwoSelect);
        var levelThreeContainer = document.createElement('div');
        levelThreeContainer.id = 'level-three-container'+selectCount;
        levelThreeContainer.className = 'styled-input';
        // 创建并初始化三级下拉列表
        var levelThreeSelect = document.createElement('select');
        levelThreeSelect.id = 'level-three'+selectCount;
        levelThreeSelect.name = 'judgingCondition';
        levelThreeSelect.className = 'styled-input';
        levelThreeContainer.style.display = 'none';
        filterRow.appendChild(levelThreeSelect);
        var levelFourContainer = document.createElement('div');
        levelFourContainer.id = 'level-four-container'+selectCount;
        levelFourContainer.className = 'styled-input';
        levelFourContainer.style.display = 'none';
        // 创建并初始化四级输入框下拉是否
        var levelFourInput = document.createElement('select');
        levelFourInput.id = 'level-four-input'+selectCount;
        levelFourInput.name = 'judgmentSelectValue';
        levelFourInput.className = 'styled-input';
        levelFourInput.style.display = 'none';
        filterRow.appendChild(levelFourInput);
        // 创建并初始化四级输入框只输入数字
        var levelFourNumber = document.createElement('input');
        levelFourNumber.id = 'level-four-inputNumber'+selectCount;
        levelFourNumber.name = 'judgmentInputValue';
        levelFourNumber.className = 'styled-input';
        levelFourNumber.type = 'number';
        levelFourNumber.style.display = 'none';
        filterRow.appendChild(levelFourNumber);
        // 创建移除按钮
        var removeButton = document.createElement('button');
        removeButton.textContent = '删除';
        removeButton.className = 'remove-buttonx';
        removeButton.onclick = () => {
            filtersContainer.removeChild(filterRow);

        };
        filterRow.innerHTML+= "<p class='grey-text'>如满足左侧设定逻辑，则不会执行任务动作</p>";
        filterRow.appendChild(removeButton);
        // 将新创建的 filterRow 添加到 filtersContainer 中
        filtersContainer.appendChild(filterRow);
    }
    function bindSelectEvents(id) {
        var levelOneSelect = document.getElementById('level-one'+id);
        var levelTwoSelect = document.getElementById('level-two'+id);//这里的值拿不到为啥
        var levelThreeSelect = document.getElementById('level-three'+id);
        var  levelFourSelect= document.getElementById('level-four-input'+id);
        var levelFourInput = document.getElementById('level-four-inputNumber'+id);
        // 初始化一级下拉菜单的事件监听器
        $(document).on('change', '#level-one'+id, function(e) {
            var selectedValue = this.value;
            if (levelTwoSelect) {//这里的值拿不到
                // 清空二级下拉菜单
                while (levelTwoSelect.firstChild) {
                    levelTwoSelect.removeChild(levelTwoSelect.firstChild);
                }
                // 根据一级选择加载二级选项
                if (selectedValue === 'patient-feature') {
                    // 加载患者特征的二级选项
                    loadLevelTwoOptionsForPatientFeature();
                } else if (selectedValue === 'patient-did-feature') {
                    // 加载患者Did特征的二级选项
                    loadLevelTwoOptionsForPatientDidFeature();
                }
            } else {
                console.error("levelTwoSelect element is not found");
            }

            // 隐藏三级和四级容器
            hideLevelThreeAndFourContainers();
        });

        // 初始化二级下拉菜单的事件监听器
        $(document).on('change', '#level-two'+id, function(e) {
            var selectedValue = this.value;
            // 清空三级下拉菜单
            while (levelThreeSelect.firstChild) {
                levelThreeSelect.removeChild(levelThreeSelect.firstChild);
            }

            // 根据二级选择加载三级选项
            if (selectedValue === '最近待执行随访距今天数' ||
                selectedValue === '最近已完成随访距今天数' ||
                selectedValue === '最近订单距今天数') {
                debugger;
                // 加载数值比较类型的三级选项
                loadLevelThreeOptionsForNumericComparison();
            } else {
                debugger;
                // 加载字符串比较类型的三级选项
                loadLevelThreeOptionsForStringComparison();
            }
            // 隐藏四级容器
            hideLevelFourContainer();
        });

        // 初始化三级下拉菜单的事件监听器
        $(document).on('change', '#level-three'+id, function(e) {
            var selectedValue = this.value;

            // 清空四级下拉菜单
            while (levelFourSelect.firstChild) {
                levelFourSelect.removeChild(levelFourSelect.firstChild);
            }
            // 根据三级选择加载四级选项
            if (selectedValue === '大于等于' ||
                selectedValue === '小于等于' ||
                selectedValue === '大于' ||
                selectedValue === '小于' ||
                selectedValue === '等于' ||
                selectedValue === '不等于') {
                // 显示输数字
                showLevelFourInput();
            } else if (selectedValue === '--等于--' || selectedValue === '--不等于--') {
                // 显示选择器
                loadLevelThreeOptionsForSelection();
                showLevelFourSelect();
            }else {
                // 显示输数字
                showLevelFourInput();
            }
        });
        // 初始化三级下拉菜单的事件监听器
        $(document).on('change', '#level-four'+id, function(e) {
            var selectedValue = this.value;
            // 根据三级选择加载四级选项
            if (selectedValue === '是' ||
                selectedValue === '否'
               ) {
                // 显示输择器
                showLevelFourSelect();
            } else {
                // 显示选数字
                showLevelFourInput();
            }
        });
        // 加载患者特征的二级选项
        function loadLevelTwoOptionsForPatientFeature() {

            var options = [
                '请选择二级分类',
                '默认触达手机号',
                '永久停止随访(脱落召回)',
                '永久停止随访(常规随访)',
                '永久停止随访(全部)',
                '最近待执行随访距今天数',
                '最近已完成随访距今天数'
            ];
            options.forEach((option, index) => {
                var newOption = document.createElement('option');
                if (newOption === '请选择二级分类') {
                    newOption.setAttribute('value', '');
                    newOption.disabled = true; // 设置为禁用状态
                    newOption.selected = true; // 设置为预选中状态
                } else {
                    newOption.value = option;
                    newOption.textContent = option;
                }
                levelTwoSelect.appendChild(newOption);
            });
            // 显示二级容器
            showLevelTwoContainer();
        }

        // 加载患者Did特征的二级选项
        function loadLevelTwoOptionsForPatientDidFeature() {
            var options = [
                '请选择二级分类',
                '最近订单距今天数',
                '永久停止随访(脱落召回)',
                '永久停止随访(常规随访)',
                '永久停止随访(全部)',
                '用药状态'
            ];
            options.forEach((option, index) => {
                var newOption = document.createElement('option');
                if (newOption === '请选择二级分类') {
                    newOption.setAttribute('value', '');
                    newOption.disabled = true; // 设置为禁用状态
                    newOption.selected = true; // 设置为预选中状态
                } else {
                    newOption.value = option;
                    newOption.textContent = option;
                }
                levelTwoSelect.appendChild(newOption);
            });

            // 显示二级容器
            showLevelTwoContainer();
        }
        // 加载数值比较类型的三级选项
        function loadLevelThreeOptionsForNumericComparison() {
            var options = [
                '请选择三级分类',
                '大于等于',
                '小于等于',
                '大于',
                '小于',
                '等于',
                '不等于'
            ];
            options.forEach((option, index) => {
                var newOption = document.createElement('option');
                if (newOption === '请选择二级分类') {
                    newOption.setAttribute('value', '');
                    newOption.disabled = true; // 设置为禁用状态
                    newOption.selected = true; // 设置为预选中状态
                } else {
                    newOption.value = option;
                    newOption.textContent = option;
                }
                levelThreeSelect.appendChild(newOption);
            });
            // 显示三级容器
            showLevelThreeContainer();
        }

        // 加载字符串比较类型的三级选项
        function loadLevelThreeOptionsForStringComparison() {
            var options = [
                '请选择三级分类',
                '等于',
                '不等于'
            ];
            debugger;
            options.forEach((option, index) => {
                var newOption = document.createElement('option');
                if (newOption === '请选择二级分类') {
                    newOption.setAttribute('value', '');
                    newOption.disabled = true; // 设置为禁用状态
                    newOption.selected = true; // 设置为预选中状态
                }else{
                    if(option==='等于'){
                        newOption.setAttribute('value','--等于--');
                    }else if(option==='不等于'){
                        newOption.setAttribute('value','--不等于--');
                    }else{
                        newOption.setAttribute('value',option);
                    }
                    newOption.value=option;
                    newOption.textContent =option;
                }


                levelThreeSelect.appendChild(newOption);
            });

            // 显示三级容器
            showLevelThreeContainer();
        }
        // 加载字符串比较类型的三级选项
        function loadLevelThreeOptionsForSelection() {
            var options = [
                '请选择',
                '是',
                '否'
            ];

            options.forEach(option => {
                var newOption = document.createElement('option');
                if (newOption === '请选择') {
                    newOption.setAttribute('value', '');
                    newOption.disabled = true; // 设置为禁用状态
                    newOption.selected = true; // 设置为预选中状态
                }
                newOption.value=option;
                newOption.textContent = option;
                levelFourSelect.appendChild(newOption);
            });

        }
        // 显示输入框
        function showLevelFourInput() {
            levelFourInput.style.display = 'block';
            levelFourSelect.style.display = 'none';
        }

        // 显示选择器
        function showLevelFourSelect() {
            levelFourInput.style.display = 'none';
            levelFourSelect.style.display = 'block';
        }

        // 隐藏三级和四级容器
        function hideLevelThreeAndFourContainers() {
            if (levelThreeSelect) {
                levelThreeSelect.style.display = 'none';
            }
            if (levelFourInput) {
                levelFourInput.style.display = 'none';
            }
            if (levelFourSelect) {
                levelFourSelect.style.display = 'none';
            }
        }

        // 隐藏四级容器
        function hideLevelFourContainer() {
            if (levelFourInput) {
                levelFourInput.style.display = 'none';
            }
            if (levelFourSelect) {
                levelFourSelect.style.display = 'none';
            }

        }

        // 显示二级容器
        function showLevelTwoContainer() {
            document.getElementById('level-two'+id).style.display = 'block';
        }

        // 显示三级容器
        function showLevelThreeContainer() {
            document.getElementById('level-three'+id).style.display = 'block';
        }
    }
    function bindTabEvents(carNum) {
        console.log("carNum"+carNum);
        var flag = true ;
        var TJ = '';

        var  renwdongz='';//任务动作
        $('#filtersContainer'+carNum).on('change', '.styled-input', function(e) {
            // 获取当前选中的值
            var selectedValue = e.target.value;

            bindSelectEvents(this.id.substring(9)); // 调用 bindSelectEvents 函数
        });
        // 绑定 change 事件
        $(document).on('change', '#ts'+carNum, function(e) {
            var selectedValue = $(this).val();
            if (selectedValue === "周期节点" && flag) {
                flag = false;
                $('#span'+carNum).remove();
                var addNodeOne ='<span id="span'+carNum+'"> 每 '+
                    '<input type="number" name="createTaskEvery" placeholder="请输入" class="styled-input" value="">' +
                    "  天生成任务，共执行  " +
                    '<input type="number" name="createTaskExecutionTimes" placeholder="请输入" class="styled-input" value="">次</span>'

                $('#scrw'+carNum).after(addNodeOne);
            }if (selectedValue === "单次节点" && TJ=='时间条件') {
                flag = true;
                $('#span'+carNum).remove();
                var addNodeOne ="  <span id=\"span"+carNum+"\">第  " +
                    '<input type="number" id="rwday'+carNum+'" name="createTaskDi" placeholder="请输入" class="styled-input" value="">' +
                    "  天生成任务 </span>" ;
                $('#scrw'+carNum).after(addNodeOne);
            }
            if (selectedValue === "单次节点" && TJ=='事件条件') {
                flag = true;
                $('#span'+carNum).remove();
                var addNodeOne ='<span id="span'+carNum+'"> 当 '+
                    '<select name="createTaskWhen" id="scrw-t'+carNum+'" class="styled-input">' +
                    '<option value="">请选择</option>' +
                    ' <option value="最近订单D值">最近订单D值(剩余用药天数)</option>' +
                    '<option value="其他值">其他值</option>' +
                    '</select>' +
                    "  为" +
                    '<input type="number" name="createTaskTriggerValue" placeholder="请输入" class="styled-input" value="">触发动作'
                $('#scrw'+carNum).after(addNodeOne);
            }
            if (selectedValue === "单次节点" && TJ=='' ) {
                flag = true;
                $('#span'+carNum).remove();
                var addNodeOne ="  <span id=\"span"+carNum+"\">第  " +
                    '<input type="number" id="scrw-t'+carNum+'" name="createTaskDi" placeholder="请输入" class="styled-input" value="">' +
                    "  天生成任务 </span>" ;
                $('#scrw'+carNum).after(addNodeOne);
            }
        });
        // 绑定 change 事件
        $(document).on('change', '#scrw'+carNum, function(e) {
            var selectedValue = $(this).val();
            if (selectedValue === "事件条件" && flag===false) {
                TJ='事件条件';
                $('#span'+carNum).remove();
                var addNodeOne ='<span id="span'+carNum+'"> 当 '+
                    '<select name="createTaskWhen" id="scew-t'+carNum+'" class="styled-input">' +
                    '<option value="">请选择</option>' +
                    ' <option value="最近订单D值">最近订单D值(剩余用药天数)</option>' +
                    '<option value="其他值">其他值</option>' +
                    '</select>' +
                    "  为" +
                    '<input type="number" name="createTaskTriggerValue" placeholder="请输入" class="styled-input" value="">触发动作'+
                    " 共执行  " +
                    '<input type="number" name="createTaskExecutionTimes" placeholder="请输入" class="styled-input" value="">次</span>'
                $('#scrw'+carNum).after(addNodeOne);
            } if (selectedValue === "事件条件" && flag===true) {
                TJ='事件条件';
                $('#span'+carNum).remove();
                var addNodeOne ='<span id="span'+carNum+'"> 当 '+
                    '<select name="createTaskWhen" id="scrw-t'+carNum+'" class="styled-input">' +
                    '<option value="">请选择</option>' +
                    ' <option value="最近订单D值">最近订单D值(剩余用药天数)</option>' +
                    '<option value="其他值">其他值</option>' +
                    '</select>' +
                    "  为" +
                    '<input type="number" name="createTaskTriggerValue" placeholder="请输入" class="styled-input" value="">触发动作'
                $('#scrw'+carNum).after(addNodeOne);
            }if (selectedValue === "时间条件" && flag===false) {
                TJ='时间条件';
                $('#span'+carNum).remove();
                var addNodeOne ='<span id="span'+carNum+'"> 每 '+
                    '<input type="number" name="createTaskEvery" placeholder="请输入" class="styled-input" value="">' +
                    "  天生成任务，共执行  " +
                    '<input type="number" name="createTaskExecutionTimes" placeholder="请输入" class="styled-input" value="">次</span>'
                $('#scrw'+carNum).after(addNodeOne);
            }if (selectedValue === "时间条件" && flag===true) {
                TJ='时间条件';
                $('#span'+carNum).remove();
                var addNodeOne ="  <span id=\"span"+carNum+"\">第  " +
                    '<input type="number" id="scrw-t'+carNum+'" name="createTaskDi" placeholder="请输入" class="styled-input" value="">' +
                    "  天生成任务 </span>" ;
                $('#scrw'+carNum).after(addNodeOne);
            }
        });

        // 绑定 change 事件
        $(document).on('change', '#rwdz'+carNum, function(e) {
            var chudaSelect = $(this).val();
            var roleSelect = document.getElementById("js"+carNum);

            // 清空当前的所有选项
            while (roleSelect.firstChild) {
                roleSelect.removeChild(roleSelect.firstChild);
            }
            // 根据 chudaSelect 的值添加合适的选项
            if (chudaSelect=== '表单任务') {

                var divElement = document.getElementById("rwdzID"+carNum); // 获取 div 引用
                divElement.style.display = "none";
                var divElementform = document.getElementById("rwdzform"+carNum); // 获取 div 引用
                divElementform.style.display = "block";
                renwdongz='表单任务';
                var option = document.createElement("option");
                option.value = "药师";
                option.text = "药师";
                roleSelect.appendChild(option);
                selectedOption.push("yaoshigzt" + carNum);
                // 选中药师工作台
                document.getElementById("yaoshigzt" + carNum).checked = true;
            } else if (chudaSelect === '触达任务') {
                var divElement = document.getElementById("rwdzform"+carNum); // 获取 div 引用
                divElement.style.display = "none";
                var divElementID = document.getElementById("rwdzID"+carNum); // 获取 div 引用
                divElementID.style.display = "block";
                renwdongz='触达任务';
                var option = document.createElement("option");
                option.value = "系统";
                option.text = "系统";
                roleSelect.appendChild(option);
                selectedOption.push("duanxiqudan" + carNum);
                // 选中短信
                document.getElementById("duanxiqudan" + carNum).checked = true;
            }else if (chudaSelect === '') {
                var elementsToDelete = [];
                elementsToDelete.push('duanxiqudan' + carNum);
                elementsToDelete.push('yaoshigzt' + carNum);
                var filteredArray = selectedOption.filter(item => !elementsToDelete.includes(item));
                console.log("filteredArray="+filteredArray);
                // 取消选中
                document.getElementById("duanxiqudan" + carNum).checked = false;
                document.getElementById("yaoshigzt" + carNum).checked = false;
            }

        });
    }


    $(function(){
    $("#datetimepicker-demo-3").datetimepicker({
        format: 'HH:mm:ss',
        autoclose: true
    });
    });
    document.addEventListener("DOMContentLoaded", function() {

        addNode()
        // 监听点击事件，激活指定的选项卡
        $('#addNodeSelect').click(function(e) {
            // 阻止默认行为
            //e.preventDefault();
            // 获取当前点击的选项卡链接
            var $this = $(this);
            //获取被点击的 tab标签id
            var clickedA = $(e.target);
            var new_id = clickedA[0].id
            carNum=new_id.substring(2);
            var Select = document.getElementById("rwdz"+carNum);
            if (Select) { // 确保元素存在
                var selectedOption = Select.options[Select.selectedIndex];
                console.log(selectedOption.text); // 输出选中文本
                if(selectedOption.text =='请选择'){
                    document.getElementById("duanxiqudan" + carNum).checked = false;
                }else {
                    document.getElementById("duanxiqudan" + carNum).checked = true;
                }
            }
            var Select = document.getElementById("rwdz" + carNum);
            if (Select) { // 确保元素存在
                var selectedOption = Select.options[Select.selectedIndex];
                console.log(selectedOption.text); // 输出选中文本
                if(selectedOption.text =='请选择'){
                    document.getElementById("yaoshigzt" + carNum).checked = false;
                }else {
                    document.getElementById("yaoshigzt" + carNum).checked = true;
                }

            }
            // 将目标内容区滚动到视口中央
            $('html, body').animate({
                scrollTop: $(target).offset().top - ($(window).height() / 2)
            }, 500); // 500毫秒动画时间
        });
        // 初始绑定
        bindTabEvents(carNum);

    });

    /* 添加节点配置 */
    function addNode(){
        count++;

        // 生成 ibox 容器
        if(count===1){
            c = "active";
            t = "true"
        }else{
            c="";
            t="false"
        }
        var addNode = '<div id="tab-' + count + '" class="tab-pane '+c+'">' +
            '<div class="panel-body">'+
            '<strong>激活节点:</strong>'+
            "  按  " +
            '<select name="activateStructures" id="jhjd' + count + '" class="styled-input">' +
            '<option value="">请选择</option>' +
            '<option value="创建计划">创建计划</option>' +
            '</select>' +
            "  第  " +
            '<input type="number" name="activateWhichDay" placeholder="规格" class="styled-input" value="">' +
            "  天激活  "+
            '<select name="activateNodeRule" id="ts' + count + '" class="styled-input">' +
            '<option value="单次节点">单次节点</option>' +
            '<option value="周期节点">周期节点</option>' +
            '</select>' +
            '<p>'+
            '</p id="sctask">'+
            '<strong>生成任务:</strong>'+
            "  按  " +
            '<select name="createTaskStructures" id="scrw' + count + '" class="styled-input">' +
            '<option value="">请选择</option>' +
            '<option value="时间条件">时间条件</option>' +
            '<option value="事件条件">事件条件</option>' +
            '</select>' +
            "  <span id=\"span" + count + "\">第  " +
            '<input type="number" id="createTaskDi' + count + '" name="createTaskDi" placeholder="请输入" class="styled-input" value="">' +
            "  天生成任务 </span>"+' &nbsp;<a href="#" onclick="toTask()" id=toTask"">添加过滤条件</a>' +
            "<div id=\"filtersContainer" + count + "\" name=\"filtersContainer\"></div>" +
            '<p>'+
            '</p>'+
            '<strong>任务动作:  &emsp;&nbsp;</strong>'+
            '<select name="taskActionMode" id="cj' + count + '" class="styled-input">' +
            '<option value="创建">创建</option>' +
            '</select>' +
            '&emsp;&nbsp;&nbsp;' +
            '<select name="taskActionTaskType" id="rwdz' + count + '" class="styled-input">' +
            '<option value="">请选择</option>' +
            '<option value="表单任务">表单任务</option>' +
            '<option value="触达任务">触达任务</option>' +
            '</select>' +
            "  类型，由角色  " +
            '<select name="taskActionRole" id="js' + count + '" class="styled-input">' +
            '<option value=""></option>' +
            '<option value="药师">药师</option>' +
            '<option value="系统">系统</option>' +
            '</select>' +
            '  执行  '+
            '<p>'+
            '</p>'+
            '<strong>执行任务: </strong>生成后第&nbsp;'+
            '<input type="number" name="generationDaysAfter" placeholder="请输入" class="styled-input" value="">' +
            '  天  ' +
            '<input type="text" name="generationHMS" placeholder="请输入时间（时分秒）" id="datetimepicker-demo-3"  class="styled-input" value="">' +
            '  执行任务  ' +
            '<p>'+
            '</p>'+
            '<strong>&emsp;&emsp;&emsp;&emsp;&nbsp;&nbsp;</strong>随访主题&nbsp;'+
            '<select name="followUpSubject" id="sfzt' + count + '" class="styled-input">' +
            '<option value="">请选择</option>' +
            '<option value="用药指导">用药指导</option>' +
            '<option value="脱落召回">脱落召回</option>' +
            '<option value="常规随访">常规随访</option>' +
            '</select>' +
            '<p>'+
            '</p>'+
            '<strong>&emsp;&emsp;&emsp;&nbsp;&nbsp;</strong>任务有效期&nbsp;'+
            '<input type="number" name="taskValidity" placeholder="请输入" class="styled-input" value="">&emsp;天' +
            '<p>'+
            '</p>'+
            '<strong>&emsp;&emsp;&emsp;&emsp;&nbsp;&nbsp;</strong>任务素材&nbsp;'+
            '<select name="taskMaterial" id="1-' + count + '" class="styled-input">' +
            '<option value="表单">表单</option>' +
            '<option value="表单2">表单2</option>' +
            '</select>' +
            '<p>'+
            '</p><div id="rwdzform' + count + '" class="myDivrwdz">'+
            '<strong>&emsp;&emsp;&emsp;&emsp;&nbsp;&nbsp;</strong>使用表单&nbsp;'+
            '<select name="useForm" id="2-' + count + '" class="styled-input">' +
            '<option value="">请选择</option>' +
            '<option value="单任务表单">单任务表单</option>' +
            '<option value="随访任务表单">随访任务表单</option>' +
            '<option value="脱落召回随访表单">脱落召回随访表单</option>' +
            '</select>' +
            '</div><p>'+
            '</p><div id="rwdzID' + count + '" class="myDivrwdz">'+
            '<strong>&emsp;&emsp;&emsp;&emsp;&nbsp;&nbsp;</strong>短信ID&emsp;&nbsp;'+
            '<input type="text" name="smsId" class="styled-input" placeholder="请输入短信ID" value="">' +
            '</div><p>'+
            '</p>'+
            '<strong>&emsp;&emsp;&emsp;&emsp;&nbsp;</strong>下发渠道&nbsp;'+
            '<input type="radio" id="duanxiqudan' + count + '" name="deliveryChannel" class="form-check-radio" value="短信"> 短信 ' +
            '<input type="radio" id="yaoshigzt' + count + '" name="deliveryChannel" class="form-check-radio" value="药师工作台"> 药师工作台 ' +
            '</div>'+
            '</div>';
        // 添加到容器
        var  NodeSelect =  '<li id="li-' + count + '" class="'+c+'"><a data-toggle="tab" href="#tab-' + count + '" aria-expanded="'+t+'">  <span class="your-class-for-nodes" id="jd' + count + '">' +
            '节点' + count +'</span><span class="close-tab" onclick="deleteNode(\'' + count + '\')"><i class="fa fa-times"></i></span></a></li>';
        $('#addNode').append(addNode);
        $('#addNodeSelect').append(NodeSelect);
// 主动重新绑定事件
        bindTabEvents(count);
    }
    function doSubmit2(index, layero) {
        var rows = layero.find("iframe")[0].contentWindow.selectTableObject();
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var tableBody = $('#drugInfoTable tbody');

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

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

                dvalueDays: item.dvalueDays,
            };

            // 检查是否已经存在该药品
            if (!isProductExist(columnsData.productId)) {
                // 向表格中添加一行
                var row = `
               <tr data-product-id="${columnsData.productId}">
                    <td><button class="btn btn-danger delete-drug-btn" data-product-id="${columnsData.productId}">删除重选择药品</button></td>
                    <td>${columnsData.productCode}</td>
                    <td>${columnsData.productName}</td>
                    <td>${columnsData.specification}</td>
                </tr>
            `;
                tableBody.append(row);
                updateDrugCount(); // 更新药品数量
            } else {
                $.modal.alertWarning(`药品 [ ${columnsData.productName} ] 已经添加了`);
            }
        });

        $.modal.close(index);
    }
    function deleteRow(productId) {
        $.modal.confirm("确认删除该药品吗？", function() {
            // 使用 attr 而不是直接拼接字符串，以防止潜在的XSS攻击
            var selector = `[data-product-id="${productId}"]`;
            $(selector).remove();
            updateDrugCount(); // 更新药品数量
        });
    }
    function isProductExist(productId) {
        // 检查表格中是否已经存在该药品
        return $('#drugInfoTable tbody tr[data-product-id="' + productId + '"]').length > 0;
    }

    // 更新所有行的序号
    function updateSerialNumbers() {
        $('#drugInfoTable tbody tr').each(function(index) {
            $(this).find('td:first-child').text(index + 1); // 序号从1开始
        });
    }
    // 更新药品数量显示
    function updateDrugCount() {
        var count = $('#drugInfoTable tbody tr').length;
        $('#drug-count').text(count);
    }
    function deleteNode(id) {
        if(count===0){
            return false
        }
        count--;
        // 删除 ibox 容器
        $('#li-' + id).remove();
        $('#tab-' + id).remove();
        // 遍历所有剩余的节点，更新它们的编号
        $('.your-class-for-nodes').each(function() {

            // 获取当前节点的 id
            let currentId = parseInt(this.id.replace('jd', '')); // 提取数字部分
            // 如果当前节点的 id 大于被删除的节点的 id，更新编号
            if (currentId > id) {
                // 创建一个新的 id
                let newId = 'jd' + (currentId - 1);
                // 更新节点的 id 和文本内容
                $(this).attr('id', newId).text('节点' + (currentId - 1));
                let closeTabElement = $(this).closest('li').find('.close-tab');
                if (closeTabElement.length > 0) {
                    // 更新 onclick 属性中的参数
                    let onclickAttr = closeTabElement.attr('onclick');
                    let updatedOnclickAttr = onclickAttr.replace(/\d+/g, newId.substring(2));
                    closeTabElement.attr('onclick', updatedOnclickAttr);
                }
                $(this).closest('li').attr('id', 'li-' + newId.substring(2));

                // 更新 a 标签的 href 属性
                let aTag = $(this).closest('li').find('a');
                if (aTag.length > 0) {
                    let hrefAttr = aTag.attr('href');
                    let updatedHrefAttr = hrefAttr.replace(/\d+/g, newId.substring(2));
                    aTag.attr('href', updatedHrefAttr);
                }
            }

        });

    }
    //获取药品表格数据
    function getTableData() {
        var tableRows = [];

        $('#drugInfoTable tbody tr').each(function(index, row) {
            var rowData = {
                productId: $(row).data('product-id'),
                productCode: $(row).find('td:eq(1)').text().trim(), // 药品编码
                productName: $(row).find('td:eq(2)').text().trim(), // 药品名
                specification: $(row).find('td:eq(3)').text().trim(), // 规格
            };
            tableRows.push(rowData);
        });

        return tableRows;
    }
</script>
<style>



    .myDivrwdz {
        display: none; /* 初始状态为不显示 */
    }

    .grey-text {
        padding-right: 5px;
        padding-top: 10px;
        color: gray;
        font-family: "楷体", KaiTi, serif;
        font-size: 11px;
    }
    .filter-row {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
    }
    .filter-row input,
    .filter-row select {
        margin-right: 10px;
    }

    /*.ibox {*/
    /*    width: 1121px;*/
    /*    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;
    }


    .styled-input3 {
        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;
    }
</style>
