<template>
  <!-- 添加/编辑单页对话框 -->
  <el-dialog
    :model-value="visible"
    :title="dialogTitle"
    width="80%"
    :close-on-click-modal="false"
    @update:model-value="handleDialogClose"
  >
    <el-form
      :model="currentOnePage"
      label-width="100px"
      :rules="formRules"
      ref="onePageFormRef"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="currentOnePage.title"
          placeholder="请输入单页标题"
          maxlength="255"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="路由" prop="path">
        <el-input
          v-model="currentOnePage.path"
          placeholder="例如：/about、/contact、/privacy"
          maxlength="200"
        />
        <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
          路由地址，必须以 / 开头，例如：/about
        </div>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input
          v-model="currentOnePage.content"
          type="textarea"
          :rows="20"
          placeholder="请输入单页内容（支持代码）"
          style="font-family: 'Courier New', monospace;"
        />
        <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
          支持代码和文本内容，使用等宽字体显示
        </div>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="currentOnePage.sort"
              :min="0"
              placeholder="数字越小越靠前"
              style="width: 100%"
            />
            <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
              数字越小，排序越靠前
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="currentOnePage.status"
              :active-value="1"
              :inactive-value="0"
            />
            <div style="margin-top: 8px; font-size: 12px; color: var(--el-text-color-secondary);">
              启用后，前端可以访问该单页
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage, ElForm } from "element-plus";

// 定义单页数据类型
interface OnePage {
  id: number;
  title: string;
  content: string;
  path: string;
  sort: number;
  status: 0 | 1;
  create_time?: string;
  update_time?: string;
  delete_time?: string;
}

// Props
interface Props {
  visible: boolean;
  onepage: Partial<OnePage> | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  onepage: null,
});

// Emits
const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "save", onepage: Partial<OnePage>): void;
  (e: "cancel"): void;
}>();

// 表单引用
const onePageFormRef = ref<InstanceType<typeof ElForm>>();

// 当前操作的单页
const currentOnePage = ref<Partial<OnePage>>({
  id: 0,
  title: "",
  content: "",
  path: "",
  sort: 0,
  status: 1,
});

// 对话框标题
const dialogTitle = computed(() => {
  return props.onepage?.id && props.onepage.id > 0 ? "编辑单页" : "添加单页";
});

// 表单验证规则
const formRules = ref({
  title: [{ required: true, message: "请输入单页标题", trigger: "blur" }],
  path: [
    { required: true, message: "请输入路由", trigger: "blur" },
    {
      pattern: /^\/[a-zA-Z0-9\/_-]*$/,
      message: "路由必须以 / 开头，只能包含字母、数字、下划线、横线和斜线",
      trigger: "blur",
    },
  ],
  content: [{ required: true, message: "请输入单页内容", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序号", trigger: "blur" }],
});

// 监听props变化，更新当前单页
watch(
  () => props.onepage,
  (newOnePage) => {
    if (newOnePage) {
      currentOnePage.value = {
        ...newOnePage,
      };
    } else {
      // 重置表单
      currentOnePage.value = {
        id: 0,
        title: "",
        content: "",
        path: "",
        sort: 0,
        status: 1,
      };
    }
  },
  { immediate: true }
);

// 监听props.visible变化
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible && (!props.onepage || !props.onepage.id)) {
      // 新增时重置表单
      currentOnePage.value = {
        id: 0,
        title: "",
        content: "",
        path: "",
        sort: 0,
        status: 1,
      };
    }
  }
);

// 取消操作
const handleCancel = () => {
  emit("update:visible", false);
  emit("cancel");
};

// 处理对话框关闭
const handleDialogClose = (value: boolean) => {
  if (!value) {
    emit("update:visible", false);
    emit("cancel");
  }
};

// 保存单页
const handleSave = async () => {
  // 表单验证
  if (!onePageFormRef.value) return;
  const valid = await onePageFormRef.value.validate();
  if (!valid) return;

  // 准备提交数据
  const payload = { ...currentOnePage.value };

  // 触发保存事件
  emit("save", payload);
};
</script>

<style lang="less" scoped>
/* 对话框样式精简 */
:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 代码编辑器样式 */
:deep(.el-textarea__inner) {
  font-family: 'Courier New', 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.6;
  resize: vertical;
}
</style>

