<template>
  <div class="article-save-container">
    <div class="article-content-wrapper">
      <div class="article-header-section">
        <div class="title-container">
          <input type="text" v-model="Articleform.title" class="article-main-title" placeholder="请输入标题"
            @focus="($event.target as HTMLInputElement).placeholder = ''"
            @blur="($event.target as HTMLInputElement).placeholder = '请输入标题'" />
        </div>
        <div class="article-meta-info">
          <span class="meta-item date-item">
            <i class="el-icon-document"></i>
            <span> {{ new Date().toLocaleDateString() }} </span>
          </span>
          <span class="meta-item status-item">
            <i class="el-icon-document"></i>
            <el-select v-model="Articleform.status" placeholder="请选择状态" class="meta-select">
              <el-option v-for="item in statusoptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </span>
          <span class="meta-item category-item">
            <i class="el-icon-folder"></i>
            <el-cascader :options="categorieoptions" v-model="selectedValues" @change="handleCascaderChange"
              placeholder="选择分类和属性" class="meta-cascader">
              <template #default="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </span>
        </div>
        <div class="article-summary-section">
          <!-- 文章简介 -->
          <span class="meta-item summary-item">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入简介"
              v-model="Articleform.content">
            </el-input>
          </span>

        </div>
      </div>
      <div class="editor-container">
        <!-- 编辑区域 -->
        <MdEditor v-model="Articleform.markdownscontent" class="markdown-editor" @on-save="handleSave" noImgZoomIn
          noKatex />
      </div>
        <!-- 返回列表 -->
        <el-button class="return-btn" type="primary" @click="handleReturn">返回列表</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { categoryService, categoryAttributeService, articleService } from '@/services';
import type { Article } from '@/types/index.ts';
import { ElMessage } from 'element-plus';
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()

// 路由
import router from '@/router/Router';
const Articleform = ref<Article>({
  articleid: 0,
  title: '',
  content: '',
  attributeid: 0,
  categoryName: '',
  createdAt: '',
  updatedAt: '',
  markdownscontent: '',
})

// 用于级联选择器的值绑定
const selectedValues = ref([]);
const categorieoptions = ref([]);
const statusoptions = ref([
  {
    label: '草稿',
    value: '0'
  },
  {
    label: '发布',
    value: '1'
  },
  {
    label: '删除',
    value: '2'
  }
]);
// 编辑文章
const editArticle = globalStore.getValue('updatearticle')

if (editArticle) {
  Articleform.value = {
    ...editArticle,
    // 确保status是字符串格式，与statusoptions的value格式匹配
    status: editArticle.status !== undefined ? String(editArticle.status) : '0'
  }
}
// 初始化加载分类和属性，构建级联选择器的options
const loadCategories = async () => {
  try {
    const categories = ref([]);
    const response = await categoryService.getCategoryTree();
    if (response.code === 200) {
      categories.value = response.data;
      // 构建级联选择器的options
      categorieoptions.value = categories.value.map(category => ({
        label: category.name,
        value: category.id,
        children: category.children.map(child => ({
          label: child.attributename,
          value: child.attributeid
        }))
      }));
    } else {
      ElMessage.error('加载分类失败: ' + response.message);
    }
  } catch (error) {
    console.error('加载分类失败:', error);
  }
};

// 处理级联选择变化
const handleCascaderChange = (values) => {
  if (values && values.length > 0) {
    // 最后一个值是属性ID
    Articleform.value.attributeid = Number(values[values.length - 1]);
  } else {
    Articleform.value.attributeid = 0;
  }
};


const handleSave = (markdown) => {
  Articleform.value.markdownscontent = markdown;

  // 验证必填字段
  if (!Articleform.value.title || !Articleform.value.attributeid) {
    ElMessage.warning('请填写必填字段：标题和分类属性');
    return;
  }

  // 构建请求数据
  const articleData = {
    articleid: Articleform.value.articleid,
    title: Articleform.value.title,
    content: Articleform.value.content,
    attributeid: Number(Articleform.value.attributeid),
    status: Number(Articleform.value.status),
    viewCount: 0,
    likes: 0,
    markdownscontent: Articleform.value.markdownscontent
  };

  // console.log('发送文章数据:', articleData);
  // console.log('当前认证token是否存在:', !!localStorage.getItem('token'));
  // 根据articleid决定调用创建还是更新接口
  const savePromise = Articleform.value.articleid === 0
    ? articleService.createArticle(articleData)
    : articleService.updateArticle(Articleform.value.articleid, articleData);
  savePromise
    .then(res => {
      // console.log('API响应:', res);
      if (res.code === 200) {
        ElMessage.success(Articleform.value.articleid === 0 ? '文章创建成功' : '文章更新成功');
        // 清除全局存储中的article
        globalStore.removeValue('updatearticle');
        // 重置表单或保留编辑状态
        if (Articleform.value.articleid === 0) {
          // 创建新文章后重置表单
          Articleform.value = {
            articleid: 0,
            title: '',
            content: '',
            attributeid: 0,
            categoryName: '',
            createdAt: '',
            updatedAt: '',
            markdownscontent: ''
          };
          selectedValues.value = [];
        }

        // 返回列表页
        router.push('/home');
      } else {
        ElMessage.error(res.message || (Articleform.value.articleid === 0 ? '文章创建失败' : '文章更新失败'));
      }
    })
    .catch(err => {
      console.error('保存失败错误详情:', err);
      // 更详细的错误信息
      if (err.response) {
        console.error('错误状态码:', err.response.status);
        console.error('错误响应数据:', err.response.data);

        const operationType = Articleform.value.articleid === 0 ? '创建' : '更新';

        if (err.response.status === 401) {
          ElMessage.error('未授权访问，请先登录');
        } else if (err.response.status === 403) {
          ElMessage.error(`没有权限${operationType}文章，请检查账号权限`);
        } else if (err.response.status === 400) {
          ElMessage.error('数据验证失败: ' + (err.response.data?.message || '请检查输入'));
        } else {
          ElMessage.error(`请求被拒绝，错误代码: ${err.response.status}`);
        }
      } else {
        ElMessage.error(err.message || (Articleform.value.articleid === 0 ? '文章创建失败' : '文章更新失败'));
      }
    })
};

/**
 * 返回列表页
 */
const handleReturn = () => {
  // 确定是否返回列表页
  if (window.confirm('确定要返回列表页吗？所有未保存的更改将丢失。')) {
    // 清除全局存储中的article
    globalStore.removeValue('updatearticle');
    router.push('/home');
  }
};
// 组件挂载时加载分类和属性
onMounted(() => {
  loadCategories();
});
</script>


<style scoped>
/* 主容器 */
.article-save-container {
  min-height: 100vh;
  margin: 0;
}

/* 内容包装器 */
.article-content-wrapper {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 40px;
}

/* 文章头部区域 */
.article-header-section {
  margin-bottom: 40px;
  padding-bottom: 24px;
  border-bottom: 2px solid #ecf0f1;
}

/* 标题容器 */
.title-container {
  text-align: center;
  margin-bottom: 30px;
}

/* 文章标题 */
.article-main-title {
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  font-size: 2.5rem;
  font-weight: 700;
  line-height: 1.2;
  color: #2c3e50;
  text-align: center;
  padding: 10px 0;
  transition: all 0.3s ease;
}

.article-main-title::placeholder {
  color: #bdc3c7;
  font-weight: 600;
}

.article-main-title:focus {
  color: #2c3e50;
}

/* 文章元信息 */
.article-meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: center;
  justify-content: center;
  color: #7f8c8d;
  font-size: 0.95rem;
}

/* 元信息项 */
.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.meta-item:hover {
  color: #3498db;
}

/* 元信息选择器样式 */
.meta-select {
  width: 160px;
}

.meta-cascader {
  width: 280px;
}

/* 编辑器容器 */
.editor-container {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* Markdown编辑器样式 */
.markdown-editor {
  border-radius: 8px;
}

.return-btn {
  margin-top: 20px;
}
/* 响应式设计 - 平板 */
@media (max-width: 768px) {
  .article-content-wrapper {
    padding: 30px 20px;
    margin: 0 15px;
    border-radius: 10px;
  }

  .article-main-title {
    font-size: 2rem;
    line-height: 1.4;
  }

  .article-meta-info {
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }

  .meta-item {
    justify-content: center;
    width: 100%;
  }

  .meta-select,
  .meta-cascader {
    width: 100%;
    max-width: 300px;
  }
}
/* 文章简介区域 */
.article-summary-section {
  margin-top: 30px;
  padding: 0 30px 0 30px;
}

/* 响应式设计 - 手机 */
@media (max-width: 480px) {
  .article-save-container {
    padding: 15px 0;
  }

  .article-content-wrapper {
    padding: 20px 15px;
    margin: 0 10px;
    border-radius: 8px;
  }

  .article-main-title {
    font-size: 1.75rem;
    line-height: 1.5;
  }

  .article-meta-info {
    font-size: 0.9rem;
    gap: 12px;
  }

  .meta-select,
  .meta-cascader {
    max-width: 100%;
  }
}
/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .article-save-container {
    background-color: #1a1a1a;
  }

  .article-content-wrapper {
    background-color: #2d2d2d;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  .article-header-section {
    border-bottom-color: #444;
  }

  .article-main-title {
    color: #f0f0f0;
  }

  .article-main-title::placeholder {
    color: #666;
  }

  .article-meta-info {
    color: #bbb;
  }

  .meta-item:hover {
    color: #4a9eff;
  }
}
/* 级联选择器ul元素自适应高度 */
:deep(.el-cascader-menu__list) {
  height: auto !important;
  max-height: none !important;
  overflow-y: visible !important;
}

/* 确保级联选择器的每个菜单项都能正确显示 */
:deep(.el-cascader-menu) {
  height: auto !important;
  min-height: 200px;
}
</style>
