<template>
  <div id="allstyle">
    <div class="article-header-section">
      <div style="text-align: center;">
        <input type="text" v-model="Articleform.title" class="article-main-title" placeholder="请输入标题"
          @focus="($event.target as HTMLInputElement).placeholder = ''"
          @blur="($event.target as HTMLInputElement).placeholder = '请输入标题'"
          style="border: none; outline: none; background: transparent; width: 100%; font-size: 2.5rem; font-weight: 700; line-height: 1.2; text-align: center;" />
      </div>
      <div class="article-meta-info" style="text-align: center;">
        <span class="meta-item">

          
          <i class="el-icon-document"></i>
          <span> {{ new Date().toLocaleDateString() }} </span>
        </span>
        <span class="meta-item">
          <i class="el-icon-document"></i>
          <el-select v-model="Articleform.status" placeholder="请选择状态">
            <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">
          <i class="el-icon-folder"></i>
          <el-cascader :options="categorieoptions" v-model="selectedValues" @change="handleCascaderChange"
            placeholder="选择分类和属性">
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </span>
      </div>
    </div>
    <div>
      <MdEditor v-model="Articleform.markdownscontent" class="markdown-editor" @on-save="handleSave" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { 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';
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'
  }
]);
const categories = ref([]);

// 初始化加载分类和属性，构建级联选择器的options
const loadCategories = async () => {
  try {
    const response = await categoryService.getAllCategories();
    if (response.code === 200) {
      categories.value = response.data;

      // 为每个分类加载对应的属性，并构建options格式
      const optionsData = await Promise.all(
        categories.value.map(async (category) => {
          try {
            const attrResponse = await categoryAttributeService.getAttributesByCategory(category.typeid);
            const children = attrResponse.code === 200 && attrResponse.data ?
              attrResponse.data.map(attr => ({
                label: attr.attributename,
                value: attr.attributeid.toString()
              })) : [];

            return {
              label: category.typename,
              value: category.typeid.toString(),
              children
            };
          } catch (error) {
            console.error(`加载分类 ${category.typename} 的属性失败:`, error);
            return {
              label: category.typename,
              value: category.typeid.toString(),
              children: []
            };
          }
        })
      );
      categorieoptions.value = optionsData;
      console.log(optionsData);
    }
  } 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;
  }
};

// 组件挂载时加载分类和属性
loadCategories();

const handleSave = (markdown) => {
  Articleform.value.markdownscontent = markdown;
  
  // 验证必填字段
  if (!Articleform.value.title || !Articleform.value.attributeid) {
    ElMessage.warning('请填写必填字段：标题和分类属性');
    return;
  }
  
  // 构建请求数据
  const articleData = {
    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'));
  
  // 保存文章
  articleService.createArticle(articleData)
    .then(res => {
      console.log('API响应:', res);
      if (res.code === 200) {
        ElMessage.success('文章保存成功')
      } else {
        ElMessage.error(res.message || '文章保存失败')
      }
    })
    .catch(err => {
      console.error('保存失败错误详情:', err);
      // 更详细的错误信息
      if (err.response) {
        console.error('错误状态码:', err.response.status);
        console.error('错误响应数据:', err.response.data);
        
        if (err.response.status === 401) {
          ElMessage.error('未授权访问，请先登录');
        } else if (err.response.status === 403) {
          ElMessage.error('没有权限创建文章，请检查账号权限');
        } else if (err.response.status === 400) {
          ElMessage.error('数据验证失败: ' + (err.response.data?.message || '请检查输入'));
        } else {
          ElMessage.error('请求被拒绝，错误代码: ' + err.response.status);
        }
      } else {
        ElMessage.error(err.message || '文章保存失败')
      }
    })
};
</script>


<style scoped>
.error-state-container .el-button {
  margin-top: 16px;
}



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

/* 文章标题 */
.article-main-title {
  font-size: 2rem;
  color: #2c3e50;
  line-height: 1.4;
  margin-bottom: 20px;
  font-weight: 600;
  margin-top: 20px;
}

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

/* 元信息项 */
.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

/* 文章内容区域 */
.article-content-area {
  font-size: 1.05rem;
  line-height: 1.8;
  color: #34495e;
  margin-bottom: 32px;
}

/* 文章内容中的段落 */
.article-content-area p {
  margin-bottom: 16px;
  text-align: justify;
}

/* 文章内容中的二级标题 */
.article-content-area h2 {
  color: #2c3e50;
  font-size: 1.5rem;
  margin: 32px 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #ecf0f1;
  font-weight: 600;
}

/* 文章内容中的三级标题 */
.article-content-area h3 {
  color: #34495e;
  font-size: 1.3rem;
  margin: 24px 0 12px 0;
  font-weight: 600;
}

/* 文章内容中的图片 */
.article-content-area img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 20px auto;
  display: block;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 文章内容中的引用 */
.article-content-area blockquote {
  border-left: 4px solid #3498db;
  padding-left: 16px;
  color: #7f8c8d;
  margin: 16px 0;
  font-style: italic;
}

/* 文章底部区域 */
.article-footer-section {
  padding-top: 24px;
  border-top: 2px solid #ecf0f1;
  margin-bottom: 32px;
}

/* 标签列表 */
.article-tag-list {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 文章操作按钮组 */
.article-actions-group {
  display: flex;
  justify-content: flex-start;
}

/* 相关文章区域 */
.related-articles-section {
  padding-top: 32px;
  border-top: 2px solid #ecf0f1;
}

/* 相关文章标题 */
.related-articles-section h3 {
  font-size: 1.3rem;
  color: #2c3e50;
  margin-bottom: 16px;
  font-weight: 600;
}

/* 相关文章列表容器 */
.related-articles-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 相关文章卡片 */
.related-article-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

/* 相关文章卡片悬停效果 */
.related-article-card:hover {
  background-color: #e9ecef;
  transform: translateX(5px);
  border-color: #3498db;
}

.related-article-card i {
  color: #3498db;
}

.related-article-card span {
  font-size: 1rem;
  color: #495057;
  transition: color 0.3s ease;
}

.related-article-card:hover span {
  color: #3498db;
}

/* 评论区样式 */
.comment-section {
  margin-top: 32px;
}

/* 响应式设计 - 平板和手机 */
@media (max-width: 768px) {
  #article-detail-page {
    padding: 20px 0;
  }

  .article-detail-wrapper,
  .loading-state-container,
  .error-state-container,
  .empty-state-container {
    padding: 20px;
    margin: 0 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

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

  .article-meta-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    font-size: 0.9rem;
  }

  .article-content-area {
    font-size: 1rem;
    line-height: 1.7;
  }

  .article-content-area h2 {
    font-size: 1.3rem;
    margin: 24px 0 12px 0;
  }

  .article-content-area h3 {
    font-size: 1.2rem;
    margin: 20px 0 10px 0;
  }

  .related-articles-section h3 {
    font-size: 1.2rem;
  }

  .related-article-card {
    padding: 10px;
    gap: 8px;
  }

  .related-article-card span {
    font-size: 0.95rem;
  }
}

/* 响应式设计 - 小屏幕手机 */
@media (max-width: 480px) {
  .article-detail-wrapper {
    padding: 16px;
  }

  .article-main-title {
    font-size: 1.35rem;
  }

  .article-meta-info {
    font-size: 0.85rem;
  }
}
</style>
