<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
		<title>批量添加栏目</title>
		<link rel="stylesheet" href="/static/web/css/font-awesome.min.css">
		<link rel="stylesheet" href="/static/web/css/bootstrap.min.css">
		<link rel="stylesheet" href="/static/web/css/admin.css">
		<script src="/static/web/js/jquery.min.js"></script>
		<script src="/static/web/js/bootstrap.min.js"></script>
		<script src="/static/web/js/admin.main.js"></script>
	</head>
	<body>
		<div class="container-fluid">
			<ol class="breadcrumb">
				<li class="breadcrumb-item"><a href="index_body.php">后台面板</a></li>
				<li class="breadcrumb-item"><a href="catalog_main.php">网站栏目管理</a></li>
				<li class="breadcrumb-item active">批量添加栏目</li>
			</ol>
			<div class="card shadow-sm">
				<div class="card-header d-flex justify-content-between align-items-center">批量添加栏目<?php if($cfg_ai_enabled == 'Y'){;?><button type="button" id="btnAI" onclick="showAI();" class="btn btn-success btn-sm">小德AI助手</button><?php };?></div>
				<div class="card-body">
					<form name="form1" action="catalog_add.php" method="post">
						<input type="hidden" name="dopost" value="savequick">
						<input type="hidden" name="savetype" id="savetype">
						<div class="table-responsive">
							<table class="table table-borderless">
								<tbody>
									<tr>
										<td width="10%">是否支持投稿</td>
										<td width="40%">
											<label><input type="radio" name="issend" value="1" checked> 支持</label>
											<label><input type="radio" name="issend" value="0"> 不支持</label>
										</td>
										<td width="10%">目录保存位置</td>
										<td width="40%">
											<label><input type="radio" name="referpath" value="parent" checked> 默认网页目录（
												<?php
												$pardir = '{cmspath}'.$cfg_arcdir;
												if (!empty($typedir)) $pardir = $typedir.'/';
												$pardir = preg_replace("#\/{1,}#", '/', $pardir);
												echo $pardir;
												?>）</label>
											<label><input type="radio" name="referpath" value="cmspath"> 系统根目录</label>
											<input type="hidden" name="nextdir" id="nextdir" value="<?php echo $pardir;?>">
											<span id="pathtype" style="display:none"><input type="radio" name="referpath" id="truepath3" value="typepath">所属栏目所属目录</span>
										</td>
									</tr>
									<tr>
										<td>所属栏目</td>
										<td>
											<select name="reid" onchange="showSeltype(this);" class="admin-input-sm">
												<option value="0">选择所属栏目</option>
												<?php echo $typeOptions;?>
											</select>
											<span>（默认为顶级栏目）</span>
										</td>
										<td>文档模型</td>
										<td>
											<select name="channeltype" id="channeltype" onChange="ParTemplet(this);" class="admin-input-sm">
												<?php
												foreach($channelArray as $k=>$arr)
												{
													if ($k==$channelid) echo "<option value='{$k}' selected>{$arr['typename']} {$arr['nid']}</option>";
													else  echo "<option value='{$k}'>{$arr['typename']} {$arr['nid']}</option>";
												}
												?>
											</select>
										</td>
									</tr>
									<tr>
										<td>栏目列表选项</td>
										<td>
											<label><input type="radio" name="isdefault" value="1" checked> 静态浏览</label>
											<label><input type="radio" name="isdefault" value="-1"> 动态浏览</label>
											<label><input type="radio" name="isdefault" value="0"> 列表第一页浏览</label>
										</td>
										<td>列表命名规则</td>
										<td>
											<input type="text" name="namerule2" id="namerule2" value="{typedir}/{tid}-{page}.html" class="admin-input-lg">
											<a href="javascript:ShowHide('helpvar1');" class="btn btn-success btn-sm">说明</a>
											<div id="helpvar1" class="alert alert-secondary my-2" style="display:none">
												<p>静态规则</p>
												<p>{tid} 栏目id</p>
												<p>{page} 栏目页码数</p>
												<p>伪静态规则（Nginx）</p>
												<p>rewrite ^/list-([0-9]+)$ /apps/list.php?tid=$1;</p>
												<p>rewrite ^/list-([0-9]+)-([0-9]+)$ /apps/list.php?tid=$1&PageNo=$2;</p>
											</div>
										</td>
									</tr>
									<tr>
										<td>文档命名规则</td>
										<td>
											<input type="text" name="namerule" id="namerule" value="{typedir}/{aid}.html" class="admin-input-lg">
											<a href="javascript:ShowHide('helpvar2');" class="btn btn-success btn-sm">说明</a>
											<div id="helpvar2" class="alert alert-secondary my-2" style="display:none">
												<p>静态规则</p>
												<p>{Y}{M}{D} 年月日</p>
												<p>{timestamp} INT类型的UNIX时间戳</p>
												<p>{aid} 文档id</p>
												<p>{pinyin} 拼音加文档id</p>
												<p>{py} 拼音部首加文档id</p>
												<p>{typedir} 栏目保存目录</p>
												<p>{cc} 日期加混编id后用转换为适合字母</p>
												<p>伪静态规则（Nginx）</p>
												<p>rewrite ^/article-([0-9]+).html$ /apps/view.php?arcID=$1;</p>
												<p>rewrite ^/article-([0-9]+)-([0-9]+).html$ /apps/view.php?aid=$1&pageno=$2;</p>
											</div>
										</td>
										<td>默认页的名称</td>
										<td><input type="text" name="defaultname" value="index.html" class="admin-input-lg"></td>
									</tr>
									<tr>
										<td colspan="4">
											<table id="addQuick" class="table">
												<thead>
													<tr>
														<td scope="col">排序</td>
														<td scope="col">顶级栏目名称</td>
														<td scope="col">子栏目名称（英文逗号隔开，如：栏目一,栏目二）</td>
														<td scope="col"><button type="button" class="btn btn-success btn-sm add">添加</button></td>
													</tr>
												</thead>
												<tbody>
													<tr>
														<td class="rank">
															<input type="hidden" name="posttype" class="pubinputs">
															<input type="text" name="rank" value="1" class="pubinputs admin-input-sm">
														</td>
														<td><input type="text" name="toptype" class="pubinputs admin-input-lg"></td>
														<td><input type="text" name="sontype" class="pubinputs w-100"></td>
														<td><button name="" type="button" class="btn btn-danger btn-sm del">删除</button></td>
													</tr>
													<?php for($i=2;$i<=10;$i++) {?>
													<tr class="repeat">
														<td class="rank">
															<input type="hidden" name="posttype<?php echo $i;?>" value="<?php echo $i;?>">
															<input type="text" name="rank<?php echo $i;?>" value="<?php echo $i;?>" class="pubinputs admin-input-sm">
														</td>
														<td><input type="text" name="toptype<?php echo $i;?>" class="pubinputs admin-input-lg"></td>
														<td><input type="text" name="sontype<?php echo $i;?>" class="pubinputs w-100"></td>
														<td><button name="" type="button" class="btn btn-danger btn-sm del">删除</button></td>
													</tr>
													<?php }?>
												</tbody>
											</table>
											<table id="addQuickRel" class="table" style="display:none">
												</thead>
													<tr>
														<td scope="col">排序</td>
														<td scope="col">栏目名称</td>
														<td scope="col"><button type="button" class="btn btn-success btn-sm addrel">添加</button></td>
													</tr>
												</thead>
												<tbody>
													<tr>
														<td class="rank">
															<input type="hidden" name="posttype" class="pubinputs">
															<input type="text" name="rank" value="1" class="pubinputs admin-input-sm">
														</td>
														<td><input type="text" name="reltype" class="pubinputs admin-input-lg"></td>
														<td><button name="" type="button" class="btn btn-danger btn-sm del">删除</button></td>
													</tr>
													<?php for($i=2;$i<=10;$i++) {?>
													<tr class="repeat">
														<td class="rank">
															<input type="hidden" name="posttype<?php echo $i;?>" value="<?php echo $i;?>">
															<input type="text" name="rank<?php echo $i;?>" value="<?php echo $i;?>" class="pubinputs admin-input-sm">
														</td>
														<td><input type="text" name="reltype<?php echo $i;?>" class="pubinputs admin-input-lg"></td>
														<td><button type="button" class="btn btn-danger btn-sm del">删除</button></td>
													</tr>
													<?php }?>
												</tbody>
											</table>
										</td>
									</tr>
									<tr>
										<td colspan="4" align="center">
											<button type="submit" class="btn btn-success btn-sm">保存</button>
											<a href="catalog_main.php" class="btn btn-outline-success btn-sm">返回</a>
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</form>
				</div>
			</div>
		</div>
		<div id="mdlAI" class="modal fade" tabindex="-1" aria-hidden="true">
			<div class="modal-dialog modal-xl">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">小德AI助手：批量创建栏目</h5>
						<button type="button" class="update-close" data-dismiss="modal" aria-label="Close"><i class="fa fa-times"></i></button>
					</div>
					<div class="modal-body">
						<form>
							<div class="form-group">
								<textarea id="prompt" class="form-control" style="height:160px" placeholder="请输入批量创建栏目要求，例如：我需要创建一个企业信息展示类站点"></textarea>
							</div>
							<div class="form-group">
								<label for="modelid" class="form-label">选择模型</label>
								<select id="modelid" class="form-control">
									<?php
									$dsql->SetQuery("SELECT AM.*,A.title as aititle FROM `#@__ai_model` AM LEFT JOIN `#@__ai` A ON A.id = AM.aiid ORDER BY AM.sortrank ASC,AM.id DESC");
									$dsql->Execute();
									while ($row = $dsql->GetObject()) {
									?>
										<option value="<?php echo $row->id;?>"<?php echo $row->isdefault==1?' selected' : '';?>><?php echo $row->model;?>(<?php echo $row->aititle;?>)</option>
									<?php
									}
									?>
								</select>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button id="btnAIAction" class="btn btn-success btn-sm">确定</button>
					</div>
				</div>
			</div>
		</div>
		<script>
			var $ = jQuery;
			function ShowHide(objname) {
				var obj = document.getElementById(objname);
				if (obj.style.display == "block")
					obj.style.display = "none";
				else
					obj.style.display = "block";
			};
			function ShowObj(objname) {
				var obj = document.getElementById(objname);
				obj.style.display = "block";
			};
			function HideObj(objname) {
				var obj = document.getElementById(objname);
				obj.style.display = "none";
			};
			function showSeltype(objname) {
				if (objname.value != 0) {
					$("#addQuickRel").show();
					$("#pathtype").show();
					$("#addQuick").hide();
					$("#savetype").val('rel');
				} else {
					$("#addQuickRel").hide();
					$("#addQuick").show();
					$("#pathtype").hide();
					$("#savetype").val('');
				}
			};
			$(document).ready(function() {
				//添加按钮事件
				$("#addQuick .add").click(function() {
					var id = $("#addQuick tr").prevAll("tr").length + 2;
					$("#addQuick tr:eq(1)").clone(true).addClass("repeat")
					.find(".rank input").attr("value", function() {
						return id;
					}).end().find(".pubinputs").attr("name", function() {
						return this.name + id;
					}).end().appendTo($("#addQuick"));
				});
				//删除按钮事件
				$("#addQuick .del").click(function() {
					$(this).parents(".repeat").remove();
				});
				//删除按钮事件
				$("#addQuickRel .del").click(function() {
					$(this).parents(".repeat").remove();
				});
				//添加按钮事件
				$("#addQuickRel .addrel").click(function() {
					var id = $("#addQuickRel tr").prevAll("tr").length + 1;
					$("#addQuickRel tr:eq(1)").clone(true).addClass("repeat").find(".rank input").attr("value", function() {
						return id;
					}).end().find(".pubinputs").attr("name", function() {
						return this.name + id;
					}).end().appendTo($("#addQuickRel"));
				});
			});
			function showAI() {
				$("#mdlAI").modal('show');
			}
			$("#btnAIAction").click(async function() {
				let prompt = document.getElementById("prompt").value;
				let modelid = document.getElementById("modelid").value;
				let req = await fetch(`api.php?action=get_ai_server&pname=catalog_add_quick&modelid=${modelid}&prompt=${prompt}`);
				let resp = await req.json();
				if (resp.code !== 0) {
					ShowMsg("获取服务器地址失败");
					return
				}
				let eventSource = new EventSource(resp.data);
				//新增状态跟踪变量
				let currentKey = null;
				let tagBuffer = "";
				let isClosingTag = false;
				$("#mdlAI").modal('hide');
				$("#btnAI").attr("disabled", "disabled");
				prompt = "";
				let lastChar = "";
				eventSource.onmessage = (event) => {
					const chars = event.data.split('');
					chars.forEach(char => {
						if (lastChar === '\\' && char === 'r') {
							char = '<br>';  //替换为br标签
							lastChar = "";  //清空追踪字符
						} else {
							lastChar = char;  //记录当前字符
						}
						if (char === '\\') {
							return; //如果是反斜杠，跳过处理
						}
						if (currentKey) {
							if (char === '{') {
								isClosingTag = true;
								tagBuffer = '{';
								return;
							}
							if (isClosingTag) {
								tagBuffer += char;
								if (tagBuffer === `{/${currentKey}}`) {
									if (currentKey == "content") {
										//CKEDITOR.instances["content"].setReadOnly(false);
									} else {
										const input = document.querySelector(`[name="${currentKey}"]`);
										if (input) $(input).prop("disabled", false).removeClass("disabled"); //恢复输入状态
									}
									currentKey = null;
									isClosingTag = false;
									tagBuffer = "";
									return;
								}
								if (!`{/${currentKey}}`.startsWith(tagBuffer)) {
									if (currentKey == "content") {
										CKEDITOR.instances["content"].insertHtml(tagBuffer);
									} else {
										const input = document.querySelector(`[name="${currentKey}"]`);
										if (input) input.value += tagBuffer;
									}

									isClosingTag = false;
									tagBuffer = "";
								}
							} else {
								if (currentKey == "content") {
									CKEDITOR.instances["content"].insertHtml(char);
								} else {
									const input = document.querySelector(`[name="${currentKey}"]`);
									if (input) {
										input.value += char;
										input.scrollTop = input.scrollHeight; //滚动到底部
									}
								}
							}
						} else {
							if (char === '{') {
								tagBuffer = '{';
							} else if (tagBuffer.startsWith('{')) {
								tagBuffer += char;
								if (char === '}') {
									const match = tagBuffer.match(/{([^>]+)}/);
									if (match) {
										currentKey = match[1];
										if (currentKey == "content") {
											//CKEDITOR.instances["content"].setReadOnly(true);
											CKEDITOR.instances["content"].setData("")
										} else {
											const input = document.querySelector(`[name="${currentKey}"]`);
											if (input) {
												$(input).prop("disabled", true).addClass("disabled"); //仅禁用当前输入框
												input.value = "";
											}
										}
									}
									tagBuffer = "";
								}
							}
						}
					});
				};
				eventSource.onerror = (error) => {
					if (error.target.readyState === EventSource.CONNECTING) {
						ShowMsg("连接失败，请确保您已开启并正确配置了DedeBIZ小德AI助手。 <a class='text-success' href='https://www.dedebiz.com/ai?from=dedebiz' target='_blank'>如何配置？</a>");
					} else if (typeof error.data!=="undefined" && error.data !== "" && error.target.readyState !== EventSource.CLOSED) {
						ShowMsg(error.data);
					}
					$("#btnAI").prop("disabled", false);
					eventSource.close();
				};
				//监听特定事件close
				eventSource.addEventListener('close', (event) => {
					console.log('SSE connection closed:', event.data);
					$("#btnAI").prop("disabled", false);
					eventSource.close(); //关闭连接
				});
			});
		</script>
	</body>
</html>