<link rel="stylesheet" href="<%=resource%>/css/common.css?v=6.1.2">

<style>
 
    #appContainer {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
    }
    

.arrow {
    width: 12px; 
    height: 12px; 
    background-image: url('<%=resource%>/icons/arrow.png'); 
    background-size: contain; 
    background-repeat: no-repeat; 
    transition: transform 0.3s ease; 
    display: inline-block; 
    transform: rotate(0deg); 
}
.arrow.expanded {
    transform: rotate(90deg); 
}

    .category {
        width: 100%;
        margin-bottom: 20px;
    }
    .app-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        margin-top: 5px;
        flex-direction: column;
    }
    .app-item {
        width: 140px; /* 固定宽度 */
        box-sizing: border-box;
        padding: 5px;
        display: flex;
        align-items: center; 
    }
    .app-items-row {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .app-item label {
        display: flex;
        align-items: center; 
        width: 100%; 
        text-align: left; 
    }
    

    .app-item input[type="checkbox"] {
        margin: 0;
        vertical-align: middle;
        position: relative;
        top: 0;
    }
    
    .app-item img {
        vertical-align: middle;
        display: inline-block;
    }
    
    .app-item label div {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    h2 {
        margin-bottom: 10px; 
    }
    .category-title {
        display: flex;
        justify-content: space-between;
        align-items: center; 
        width: 100%;
        cursor: pointer; 
        margin-bottom: 10px; 
    }
    .category-name {
        font-size: 14px; 
        font-weight: normal;
    }

    .category-title div {
        gap: 6px; 
    }

    .select-all-btn {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 4px 8px;
        border-radius: 3px;
        cursor: pointer;
        font-size: 12px;
        margin-left: 10px;
    }

    .select-all-btn:hover {
        background-color: #45a049;
    }

    .select-all-btn.selected {
        background-color: #f44336;
    }

    .select-all-btn.selected:hover {
        background-color: #da190b;
    }

    .select-all-container {
        display: flex;
        align-items: center;
        margin: 5px 0;
        padding: 3px 0;
        border-bottom: 1px solid #eee;
        width: 100%;
        gap: 5px;
    }
    
    .select-all-container input[type="checkbox"] {
        margin: 0;
        vertical-align: middle;
        position: relative;
        top: 0;
    }

    .select-all-label {
        font-size: 12px;
        color: #666;
        cursor: pointer;
    }

    @media (max-width: 600px) {
        .app-item {
            width: 25%; 
        }
    }


</style>

<script type="text/javascript">//<![CDATA[
	const data2 = {
            "class_list": [
                {
                    "name": "game",
                    "app_list": Array.from({length: 20}, (_, i) => `${1000 + i + 1},App ${i + 1}`)
                },
                {
                    "name": "video",
                    "app_list": Array.from({length: 20}, (_, i) => `${2000 + i + 1},App ${i + 1}`)
                }
            ]
        };

		const data = {
            "class_list": [
                {
                    "name": "game",
                    "app_list": ["1001,app 1","1002,app 2"]
                },
                {
                    "name": "video",
                    	"app_list": ["2001,app 1","2002,app 2"]
                }
            ]
        };
		let app_filter_data = [];
        const selectedAppIds = [1001, 1002, 1003];

		function init_data2() {
			// new XHR().get('<%=url('admin/network/class_list')%>', null,
			// 	function (x, data) {
			// 		console.log(data);
			// 		renderAppList(data);
			// 	}
			// );
			renderAppList(data)
		}

		
		function init_data() {
			getAppFilterData().then(() => {
				getClassListData();
			});
			getAppFilterBaseData(); 
		}

		function getAppFilterData() {
			return new Promise((resolve, reject) => {
				new XHR().get('<%=url('admin/network/get_app_filter')%>', null,
					function (x, data) {
						if (Array.isArray(data.app_list)) {
							app_filter_data = data.app_list;
						}
						resolve(); 
					}
				);
			});
		}

		function getClassListData() {
			new XHR().get('<%=url('admin/network/class_list')%>', null,
				function (x, data) {
					renderAppList(data);
				}
			);
		}

        function renderAppList(data) {
            const container = document.getElementById('appContainer');
            container.innerHTML = ''; 

            data.class_list.forEach((category, index) => {
                const categoryTitle = document.createElement('div');
                categoryTitle.className = 'category-title'; 

                const categoryName = document.createElement('span');
                categoryName.textContent = `${category.name} (${category.app_list.length} <%:items%>)`;
                categoryName.className = 'category-name';

                const rightContainer = document.createElement('div');
                rightContainer.style.display = 'flex'; 
                rightContainer.style.alignItems = 'center'; 

                const appCount = document.createElement('span');
                const selectedCount = category.app_list.filter(app => 
                    app_filter_data.includes(parseInt(app.split(',')[0]))
                ).length;
                appCount.textContent = `<%:Selected%> ${selectedCount} <%:items%>`; 
                appCount.className = 'app-count'; 

                const arrow = document.createElement('span');
                arrow.className = 'arrow'; 

                rightContainer.appendChild(appCount);
                rightContainer.appendChild(arrow);

                categoryTitle.appendChild(categoryName);
                categoryTitle.appendChild(rightContainer);
                container.appendChild(categoryTitle);

                const appList = document.createElement('div');
                appList.className = 'app-list';
                
                if (index === 1 || index === 2) {
                    appList.style.display = 'flex';
                    arrow.classList.add('expanded');
                } else {
                    appList.style.display = 'none';
                }

                // 添加全选容器到应用列表内部
                const selectAllContainer = document.createElement('div');
                selectAllContainer.className = 'select-all-container';

                // 添加全选复选框
                const selectAllCheckbox = document.createElement('input');
                selectAllCheckbox.type = 'checkbox';
                selectAllCheckbox.checked = selectedCount === category.app_list.length;
                selectAllCheckbox.title = selectedCount === category.app_list.length ? '<%:Deselect All%>' : '<%:Select All%>';

                // 添加全选标签
                const selectAllLabel = document.createElement('span');
                selectAllLabel.className = 'select-all-label';
                selectAllLabel.textContent = '<%:Select All%>';

                selectAllContainer.appendChild(selectAllCheckbox);
                selectAllContainer.appendChild(selectAllLabel);
                appList.appendChild(selectAllContainer);

                // 创建应用项目行容器
                const appItemsRow = document.createElement('div');
                appItemsRow.className = 'app-items-row';

                categoryTitle.onclick = function(e) {
                    if (appList.style.display === 'none') {
                        appList.style.display = 'flex';
                        arrow.classList.add('expanded');
                    } else {
                        appList.style.display = 'none';
                        arrow.classList.remove('expanded');
                    }
                };

                // 为全选复选框添加change事件
                selectAllCheckbox.onchange = function(e) {
                    e.stopPropagation(); // 阻止事件冒泡
                    toggleSelectAll(category, selectAllCheckbox, appCount);
                };

                // 为全选标签添加点击事件
                selectAllLabel.onclick = function(e) {
                    e.stopPropagation(); // 阻止事件冒泡
                    selectAllCheckbox.checked = !selectAllCheckbox.checked;
                    toggleSelectAll(category, selectAllCheckbox, appCount);
                };

                category.app_list.forEach(app => {
                    const appItem = document.createElement('div');
                    appItem.className = 'app-item';

                    const label = document.createElement('label');

                    const containerDiv = document.createElement('div');
                    containerDiv.style.display = 'flex'; 
                    containerDiv.style.alignItems = 'center';
                    containerDiv.style.gap = '5px';

                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.name = 'app';
                    checkbox.value = app.split(',')[0];
                    
                    if (app_filter_data.includes(parseInt(checkbox.value))) {
                        checkbox.checked = true;
                    }

                    checkbox.onchange = function() {
                        updateCategorySelection(category, selectAllCheckbox, appCount);
                    };

                    const appDetails = app.split(',');
                    const appId = appDetails[0];
                    const appName = appDetails[1];
                    const withIcon = appDetails[2] === '1';

                    const icon = document.createElement('img');
                    icon.src = withIcon ? `<%=resource%>/app_icons/${appId}.png` : `<%=resource%>/app_icons/default.png`; 
                    icon.alt = `Icon for ${appName}`;
                    icon.style.width = '20px'; 
                    icon.style.height = '20px'; 
                    icon.style.borderRadius = '7px';
                    icon.style.verticalAlign = 'middle';
                    containerDiv.appendChild(checkbox);
                    containerDiv.appendChild(icon);
                    containerDiv.appendChild(document.createTextNode(appName));

                    label.appendChild(containerDiv);
                    appItem.appendChild(label);
                    appItemsRow.appendChild(appItem);
                });
                
                appList.appendChild(appItemsRow);
                container.appendChild(appList);
            });
        }

        function toggleSelectAll(category, selectAllCheckbox, appCount) {
            const checkboxes = document.querySelectorAll(`input[name="app"]`);
            const categoryAppIds = category.app_list.map(app => parseInt(app.split(',')[0]));
            const isAllSelected = selectAllCheckbox.checked;
            
            checkboxes.forEach(checkbox => {
                const appId = parseInt(checkbox.value);
                if (categoryAppIds.includes(appId)) {
                    checkbox.checked = isAllSelected;
                }
            });
            
            updateCategorySelection(category, selectAllCheckbox, appCount);
        }

        function updateCategorySelection(category, selectAllCheckbox, appCount) {
            const checkboxes = document.querySelectorAll(`input[name="app"]`);
            const categoryAppIds = category.app_list.map(app => parseInt(app.split(',')[0]));
            let selectedCount = 0;
            
            checkboxes.forEach(checkbox => {
                const appId = parseInt(checkbox.value);
                if (categoryAppIds.includes(appId) && checkbox.checked) {
                    selectedCount++;
                }
            });
            
            appCount.textContent = `<%:Selected%> ${selectedCount} <%:items%>`;
            
            selectAllCheckbox.checked = selectedCount === category.app_list.length;
        }

        function submitAppSelection() {
            const selectedApps = [];
            const checkboxes = document.querySelectorAll('input[name="app"]:checked');
            checkboxes.forEach(checkbox => {
                selectedApps.push(parseInt(checkbox.value));
            });

            // 将数组转换为逗号分隔的字符串
            const selectedAppsStr = selectedApps.join(',');

            console.log("app_filter_data is " + selectedAppsStr);
            new XHR().post('<%=url('admin/network/set_app_filter')%>', {
                app_list: selectedAppsStr  // 提交字符串而不是数组
            },
            function (x, data) {
                console.log("set ok");
                console.log("set_app_filter data is " + data);
                init_data();
                const modal = document.getElementById('modal');
                modal.style.display = 'flex'; 
                setTimeout(() => {
                    modal.style.display = 'none'; 
                }, 1000);
            }
            );
        }

        function submitAppFilterBase() {
            const filterSwitch = document.getElementById('filterSwitch').checked;
            const workMode = parseInt(document.getElementById('workMode').value, 10);
            const recordSwitch = document.getElementById('recordSwitch').checked;
            const data = {
                data: {
                    enable: filterSwitch ? 1 : 0, 
                    work_mode: workMode,
                    record_enable: recordSwitch ? 1 : 0
                }
            };
            console.log("submitAppFilterBase");
            new XHR().post('<%=url('admin/network/set_app_filter_base')%>', {
                
                enable: filterSwitch ? 1 : 0, 
                work_mode: workMode,
                record_enable: recordSwitch ? 1 : 0
                
            },


            function (x, data) {
                console.log("Base filter settings updated");
            }
            );



        }
 
		function submitHandle() {
			submitAppFilterBase();
			submitAppSelection();
		}

		function openModal() {
			document.getElementById('modal').style.display = 'block';
		}

		function closeModal() {
			document.getElementById('modal').style.display = 'none';
		}

        function getAppFilterBaseData() {
			console.log("getAppFilterBaseData");
            new XHR().get('<%=url('admin/network/get_app_filter_base')%>', null,
                function (x, data) {
                    if (data.data.enable == 1) {
                        document.getElementById('filterSwitch').checked = true;
                    } else {
                        document.getElementById('filterSwitch').checked = false;
                    }
                    if (data.data.record_enable == 1) {
                        document.getElementById('recordSwitch').checked = true;
                    } else {
                        document.getElementById('recordSwitch').checked = false;
                    }
                    document.getElementById('workMode').value = data.data.work_mode;
                }
            );
        }

        function redirectToUserConfig() {
            window.location.href = '<%=url('admin/services/appfilter/user')%>';
        }
        function redirectToTimeConfig() {
            window.location.href = '<%=url('admin/services/appfilter/time')%>';
        }

   
        function updateRunStatus() {
            new XHR().get('<%=url('admin/network/get_oaf_status')%>', null,
                function (x, data) {
                    const runStatusElement = document.getElementById('run_status');
                    const runDescElement = document.getElementById('run_desc');
                    const engineStatusContainer = document.querySelector('.app_filter_status:first-child');

                    if (data.data.engine_status === 1) {
                        if (data.data.config_enable == 0) {
                            runStatusElement.textContent = '<%:Not Configured%>';
                            runStatusElement.style.color = 'red';
                        } else {
                            if (data.data.enable === 1) {
                                runStatusElement.textContent = '<%:Running%>';
                                runStatusElement.style.color = 'green'; 
                                if (data.data.time_mode == 1 && data.data.filter == 1) {
                                    runDescElement.textContent = `(<%:Will close in%> ${data.data.remain_time} <%:minutes%>)`;
                                }
                            } else {
                                runStatusElement.textContent = '<%:Not Running%>';
                                runStatusElement.style.color = 'red'; 
                                if (data.data.time_mode == 1) {
                                    if (data.data.match_time == 0) {
                                        runDescElement.textContent = `(<%:Current time is not within the time range%>)`;
                                    } else {
                                        runDescElement.textContent = `(<%:Will start in%> ${data.data.remain_time} <%:minutes%>)`;
                                    }
                                } else {
                                    runDescElement.textContent = `(<%:Current time is not within the time range%>)`;
                                }
                            }
                        }
                    }
                    else{
                        runStatusElement.textContent = '<%:Not Running%>';
                        runStatusElement.style.color = 'red'; 
                        runDescElement.textContent = `(<%:oaf driver not loaded, please download the oaf.ko driver file corresponding to the kernel version of this firmware for installation, and enable auto-loading. Current kernel version is%> ${data.data.kernel_version})`;
                    }
                }
            );
        }

        window.onload = function() {
            init_data();
            updateRunStatus();
            setInterval(updateRunStatus, 5000); 
        };
//]]></script>

<div id="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
    <div style="background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; text-align: center; width: 100px; height: 70px; color: white; display: flex; justify-content: center; align-items: center;">
        <p style="margin: 0;color: white;"><%:Settings saved successfully%></p>
    </div>
</div>

<div class="cbi-section cbi-tblsection">
    <div style="max-width: 1000px; margin-left: 5px;padding: 5px;">

        <div class="app_filter_status">
            <label><%:Running Status%>:</label>
            <span id="run_status"><%:Running%></span><span id="run_desc"></span>
        </div>
        <div style="margin-top: 10px; display: flex; align-items: center;">
            <label for="filterSwitch" style="margin-right: 5px;"><%:App Filter%></label>
            <label class="switch">
                <input type="checkbox" id="filterSwitch" name="filterSwitch" />
                <span class="slider"></span>
            </label>
            <label for="recordSwitch" style="margin-left: 20px;margin-right: 5px;"><%:App Record%></label>
            <label class="switch">
                <input type="checkbox" id="recordSwitch" name="recordSwitch" />
                <span class="slider"></span>
            </label>
        </div>

        <div style="margin-top: 10px;">
            <label for="workMode"><%:Work Mode%>:</label>
            <select id="workMode" name="workMode">
                <option value="0"><%:Gateway Mode%></option>
                <option value="1"><%:Bypass Mode%></option>
            </select>
        </div>
 

        <div style="margin-top: 10px;">
            <span><%:App Selection%>:</span>
        </div>
        
        <div style="margin-top: 5px; margin-bottom: 10px;">
            <span style="font-size: 12px; color: #999;"><%:If the App you want is not in the list, you can upgrade the feature library of the official website or customize the App%></span>
        </div>
        <div id="appContainer"></div>

        <div style="display: flex; justify-content: flex-start; align-items: center;width: 600px;margin-top: 10px;">
            <div style="width: 280px; display: inline-block;">
                <label><%:Effective Time%>:</label> 
                <button type="button" class="button-check" onclick="redirectToTimeConfig()"><%:View%></button>
            </div>

            <div style="width: 280px; display: inline-block; margin-left: 10px;">
                <label><%:Effective User%>:</label> 
                <!-- <span style="color: green;">5个</span> -->
                <button type="button" class="button-check" onclick="redirectToUserConfig()"><%:View%></button>
            </div>
        </div>
        <div class="button-container">
            <button type="button" class="submit-button" onclick="submitHandle()"><%:Save%></button>
        </div>
    </div>
</div>
