<template>
  <div class="establish-component-root">
    <div class="establish-container">
      <!-- 弹出的按钮容器 -->
      <!-- <div class="expanded-buttons" :class="{ 'show': isExpanded }"> -->
      <button v-for="(btn, index) in isbuttonsave()" :class="['action-button', { 'show': isExpanded }]"
        :style="getButtonStyle(index)" :key="btn.id" @click="handleButtonClick(btn)">
        <!-- <i :class="btn.icon"></i> -->
        <span>{{ btn.label }}</span>
      </button>
      <!-- </div> -->

      <!-- 主圆形按钮 -->
      <button class="main-button" :class="{ 'active': isExpanded }" @click="toggleExpand">
        <i class="icon">+</i>
      </button>
    </div>
    <!-- 标签蒙板组件 -->
    <Transition name="modal">
      <div v-if="showAttributeModal" class="category-modal" @click.self="closeAttributeModal">
        <div class="category-modal-content">
          <div class="category-modal-header">
            <h3>新建标签</h3>
            <button class="category-modal-close" @click="closeAttributeModal">×</button>
          </div>
          <div class="category-modal-body">

            <el-select v-model="CategoryAttributeDto.categoryid"  placeholder="请选择">
              <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

            <el-input v-model="CategoryAttributeDto.name" placeholder="输入新标签" />
            <el-button type="primary"
              @click="saveAttribute(CategoryAttributeDto)">保存</el-button>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
// 组件导入和初始化
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { articleService, categoryAttributeService, nonsenseService, categoryService, loginService } from '@/services'

// 全局状态管理
import { useGlobalStore } from '@/store/globalStore'
const globalStore = useGlobalStore()
const router = useRouter()

// ==============================
// 状态管理模块
// ==============================
/**
 * 按钮展开状态
 * @type {import('vue').Ref<boolean>}
 */
const isExpanded = ref(false)

/**
 * 分类列表
 * @type {import('vue').Ref<Array<{value: string, label: string}>>}
 */
const categories = ref([])

/**
 * 标签模态框显示状态
 * @type {import('vue').Ref<boolean>}
 */
const showAttributeModal = ref(false)

/**
 * 疯言疯语模态框显示状态
 * @type {import('vue').Ref<boolean>}
 */
const isNonsenseModalVisible = ref(false)

/**
 * 疯言疯语内容
 * @type {import('vue').Ref<string>}
 */
const nonsenseContent = ref('')

/**
 * 标签数据传输对象
 * @type {import('vue').Ref<{categoryid: string, name: string}>}
 */
const CategoryAttributeDto = ref({
  categoryid: '',
  name: ''
})

// ==============================
// 按钮配置和管理模块
// ==============================

/**
 * 基础按钮配置
 * @type {Array<{id: string, label: string, icon: string}>}
 */
const baseButtons = [
  { id: 'logout', label: '登出', icon: 'icon-logout' },
  { id: 'reload', label: '刷新', icon: 'icon-reload' }
]

/**
 * 页面特定按钮配置映射
 * @type {Object.<string, Array<{id: string, label: string, icon: string}>>}
 */
const pageButtons = {
  // 文章详情页按钮
  article: [
    { id: 'edit-article', label: '修改', icon: 'icon-add-article' },
    { id: 'delete-article', label: '删除', icon: 'icon-create-category' },
    ...baseButtons
  ],

  // 首页按钮
  home: [
    { id: 'create-article', label: '新建', icon: 'icon-add-article' },
    { id: 'del-articles', label: '已删除', icon: 'icon-new-tag' },
    { id: 'unpublished-articles', label: '未发表', icon: 'icon-new-tag' },
    { id: 'published-articles', label: '已发表', icon: 'icon-new-tag' },
    ...baseButtons
  ],

  // 疯言疯语页面按钮
  nonsense: [
    { id: 'create-nonsense', label: '说说', icon: 'icon-upload-file' },
    ...baseButtons
  ],

  // 分类页面按钮
  articlelist: [
    { id: 'create-category', label: '分类', icon: 'icon-create-category' },
    { id: 'create-tag', label: '标签', icon: 'icon-create-tag' },
    ...baseButtons
  ],

  // 标签页面按钮
  tag: [
    { id: 'create-tag', label: '新建', icon: 'icon-new-tag' },
    ...baseButtons
  ],

  // 文章保存页面按钮
  articlesave: [
    { id: 'view-articles', label: '文章', icon: 'icon-new-tag' },
    ...baseButtons
  ],

  // 默认按钮
  default: baseButtons
}

/**
 * 根据当前页面返回对应的按钮配置
 * @returns {Array<{id: string, label: string, icon: string}>} 按钮配置数组
 */
const isbuttonsave = () => {
  try {
    // 获取当前页面路径名称
    // const currentPath = globalStore.getValue('localpath')?.name || 'default';
    const currentPath = router.currentRoute.value.path.split('/')[1];
    // 返回对应页面的按钮配置，如果没有则返回默认配置
    return pageButtons[currentPath] || pageButtons.default;
  } catch (error) {
    console.error('获取页面按钮配置失败:', error);
    return pageButtons.default;
  }
}

/**
 * 切换按钮展开/收起状态
 * @param {Event} event - 点击事件对象
 */
const toggleExpand = (event) => {
  isExpanded.value = !isExpanded.value
  // 防止点击弹出的按钮后再次触发主按钮的点击事件
  event.stopPropagation()
}

/**
 * 为每个按钮计算动态样式
 * @param {number} index - 按钮索引
 * @returns {Object} CSS样式对象
 */
const getButtonStyle = (index) => {
  // 计算过渡时间，确保显示时从上到下逐渐出现，隐藏时从下到上逐渐消失
  const showDelay = Math.max(0.1, 0.2 + index * 0.2);
  const hideDelay = 0.3 + index * 0.2;

  // 根据是否展开返回不同的过渡样式
  if (isExpanded.value) {
    return {
      transition: `all ${showDelay}s ease-in-out`
    };
  } else {
    return {
      transition: `all ${hideDelay}s ease-in-out`
    };
  }
};

// ==============================
// 模态框管理模块
// ==============================

/**
 * 显示标签模态框
 */
const showAttributes = () => {
  showAttributeModal.value = true
}

/**
 * 关闭标签模态框
 */
const closeAttributeModal = () => {
  showAttributeModal.value = false
}

/**
 * 显示疯言疯语模态框
 */
const showNonsenseModal = () => {
  nonsenseContent.value = '' // 清空输入框
  isNonsenseModalVisible.value = true

  ElMessageBox.prompt('请输入您的疯言疯语：', '发表疯言疯语', {
    confirmButtonText: '保存',
    cancelButtonText: '取消',
    inputPlaceholder: '在这里输入您想说的话...',
    inputType: 'textarea',
    inputRows: 4,
    showCancelButton: true
  }).then(({ value }) => {
    // 保存疯言疯语
    saveNonsense(value)
  }).catch(() => {
    // 取消操作，静默处理
  })
}

// ==============================
// 功能操作方法模块
// ==============================

/**
 * 处理错误响应的工具函数
 * @param {Error} error - 错误对象
 * @param {string} defaultMessage - 默认错误消息
 */
const handleErrorResponse = (error, defaultMessage = '操作失败') => {
  console.error('操作失败:', error)
  ElMessage.error(error.message || defaultMessage)
}

/**
 * 根据文章状态获取并跳转文章列表
 * @param {number} status - 文章状态 0:未发表 1:已发表 2:已删除
 */
const getButtonsByStatus = (status) => {
  globalStore.removeValue('articlestatus')
  globalStore.setValue('articlestatus', {
    status: status
  })
  
  // 跳转文章列表页面，添加时间戳参数确保页面刷新
  try {
    const timestamp = new Date().getTime();
    router.push({ path: `/home/aericlestatus`, query: { t: timestamp } })
  } catch (error) {
    console.error('页面跳转失败:', error)
  }
}

/**
 * 保存疯言疯语
 * @param {string} content - 疯言疯语内容
 */
const saveNonsense = (content) => {
  if (!content || content.trim() === '') {
    ElMessage.warning('内容不能为空')
    return
  }

  // 调用服务保存疯言疯语
  nonsenseService.createNonsense({
    content: content.trim(),
    time: new Date(),
    status: 1
  }).then(response => {
    if (response.code === 200) {
      ElMessage.success('疯言疯语发布成功')
      // 刷新页面
      router.push({ path: `/nonsense`});
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  }).catch(err => handleErrorResponse(err, '发布失败'))
}

/**
 * 新建分类
 */
const createCategory = () => {
  ElMessageBox.prompt('请输入分类名称：', '新建分类', {
    confirmButtonText: '保存',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入分类名称',
    inputType: 'text',
    showCancelButton: true,
    // 输入验证
    inputValidator: (value) => {
      if (!value || value.trim() === '') {
        return '分类名称不能为空';
      }
      if (value.trim().length < 2) {
        return '分类名称至少需要2个字符';
      }
      return true;
    }
  }).then(({ value }) => {
    // 保存分类
    saveCategory(value.trim());
  }).catch(() => {
    // 取消操作，静默处理
  });
};

/**
 * 保存分类
 * @param {string} typename - 分类名称
 */
const saveCategory = (typename) => {
  // console.log('保存分类')
  categoryService.createCategory({
    typename: typename
  }).then(response => {
    if (response.code === 200) {
      ElMessage.success('分类创建成功');
      // 刷新页面
      router.push({ path: `/articlelist`});
    } else {
      ElMessage.error(response.message || '创建分类失败');
    }
  }).catch(err => handleErrorResponse(err, '创建分类失败'));
};

/**
 * 新建标签
 */
const createAttribute = async () => {
  showAttributes()
  try {
    const response = await categoryService.getAllCategories();
    if (response.code === 200) {
      categories.value = response.data.map(item => ({
        value: item.typeid,
        label: item.typename
      }))
    }
  } catch (error) {
    handleErrorResponse(error, '获取分类失败');
  } finally {
    // console.log(categories.value)
  }
};

/**
 * 保存标签
 * @param {{categoryid: string, name: string}} dto - 标签数据传输对象
 */
const saveAttribute = (dto) => {
  if (!dto.categoryid || !dto.name) {
    ElMessage.warning('请选择分类和输入标签名称')
    return
  }
  
  categoryAttributeService.createAttribute({
    categoryid: Number(dto.categoryid),
    attributename: dto.name
  }).then(response => {
    if (response.code === 200) {
      closeAttributeModal()
      ElMessage.success('标签创建成功');
      // 刷新页面
      router.push({ path: `/articlelist`});
    } else {
      ElMessage.error(response.message || '创建标签失败');
    }
  }).catch(err => handleErrorResponse(err, '创建标签失败'));
};

/**
 * 删除文章
 */
const deleteArticle = () => {
  const articleId = globalStore.getValue('articleInfo')?.articleid
  if (!articleId) {
    ElMessage.warning('缺少文章ID参数')
    return
  }
  
  // 确认删除
  ElMessageBox.confirm('确定删除该文章吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用删除文章接口
    articleService.deleteArticle(Number(articleId))
      .then(response => {
        if (response.code === 200) {
          ElMessage.success('文章删除成功')
          // 跳转回文章列表页
          router.push({ path: '/home' })
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      })
      .catch(err => handleErrorResponse(err, '删除失败'))
  }).catch(() => {
    // 取消删除，静默处理
  })
}

/**
 * 修改文章
 */
const updateArticle = () => {
  const articleId = globalStore.getValue('articleInfo')
  if (!articleId) {
    ElMessage.warning('缺少文章参数')
    return
  }
  
  // 确认修改
  ElMessageBox.confirm('确定修改该文章吗？', '修改确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    globalStore.setValue('updatearticle', articleId)
    router.push({ path: '/articlesave' })
  }).catch(() => {
    // 取消修改，静默处理
  })
}

/**
 * 登出系统
 */
const logout = () => {
  // 调用登出接口
  loginService.logout()
    .then(response => {
      if (response.code === 200) {
        ElMessage.success('登出成功')
        // 清空全局状态
        globalStore.clearAll()
        // 清除localStorage中的token
        localStorage.removeItem('token')
        // 跳转首页
        router.push({ path: '/' })
      } else {
        ElMessage.error(response.message || '登出失败')
      }
    })
    .catch(err => handleErrorResponse(err, '登出失败'))
}

/**
 * 刷新页面
 */
const reloadPage = () => {
  globalStore.clearAll()
}

// ==============================
// 事件处理模块
// ==============================

/**
 * 处理按钮点击事件
 * @param {{id: string, label: string, icon: string}} button - 按钮对象
 */
const handleButtonClick = (button) => {
  // console.log('点击了按钮:', button.id, button.label)

  // 使用按钮ID进行处理，更可靠且易于维护
  switch (button.id) {
    // 新增操作
    case 'create-article':
      router.push({ path: '/articlesave' })
      break
    case 'create-category':
      createCategory()
      break
    case 'create-tag':
      createAttribute()
      break
    case 'create-nonsense':
      showNonsenseModal()
      break

    // 修改操作
    case 'edit-article':
      updateArticle()
      break

    // 删除操作
    case 'delete-article':
      deleteArticle();
      break

    // 查看操作
    case 'del-articles':
      getButtonsByStatus(2)
      break
    case 'unpublished-articles':
      getButtonsByStatus(0)
      break
    case 'published-articles':
      getButtonsByStatus(1)
      break
    case 'view-articles':
      router.push({ path: '/home' })
      break

    // 系统操作
    case 'logout':
      logout();
      break
    case 'reload':
      reloadPage()
      break

    default:
      console.warn('未处理的按钮类型:', button.id, button.label)
      ElMessage.info(`功能 ${button.label} 暂未实现`)
  }

  // 点击后收起按钮菜单
  isExpanded.value = false
}

/**
 * 点击外部区域收起按钮的处理函数
 * @param {Event} e - 点击事件对象
 */
const handleClickOutside = (e) => {
  const mainButton = document.querySelector('.main-button')
  const actionButtons = document.querySelectorAll('.action-button')

  // 检查是否点击了主按钮
  const clickedMainButton = mainButton && mainButton.contains(e.target)

  // 检查是否点击了任何一个操作按钮
  const clickedActionButton = Array.from(actionButtons).some(button => button.contains(e.target))

  // 如果点击的不是主按钮和操作按钮，则收起
  if (!clickedMainButton && !clickedActionButton) {
    isExpanded.value = false
  }
}

// ==============================
// 组件生命周期
// ==============================

/**
 * 组件挂载时添加事件监听
 */
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

/**
 * 组件卸载前清理事件监听
 */
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.establish-container {
  width: 230px;
  position: fixed;
  z-index: 1000;
  bottom: 50px;
  right: -80px;
}

/* 主圆形按钮样式 */
.main-button {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #409eff;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 1001;
  margin-left: 80px;
}

.main-button:hover {
  background-color: #66b1ff;
  transform: scale(1.05);
}

.main-button.active {
  background-color: #f56c6c;
  transform: rotate(45deg);
}

.main-button.active:hover {
  background-color: #f78989;
}

.main-button .icon {
  font-style: normal;
  transition: transform 0.3s ease;
}


/* 弹出的按钮样式 */
.action-button {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 15px;
  background-color: white;
  border: 1px solid #dcdfe6;
  border-radius: 20px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  margin-bottom: 10px;
  opacity: 0;
  /* 从右侧滑入 */
}

.action-button:hover span {
  color: red;
}

.action-button i {
  margin-right: 8px;
  font-style: normal;
  color: #409eff;
  font-size: 16px;
}

.action-button span {
  color: #606266;
  font-size: 14px;
}

/* 按钮展开状态样式 */
.action-button.show {
  margin-left: 70px;
  opacity: 1;
}

/* 按钮默认状态样式 */
.action-button {
  margin-left: 150px;
  opacity: 1;
}

/* 分类蒙板样式 */
.category-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  /* 确保在任何情况下都能居中显示 */
  margin: 0;
  padding: 0;
}

.category-modal-content {
  background-color: white;
  border-radius: 10px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  /* 确保内容块在父容器中完美居中 */
}

.category-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.category-modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.category-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.category-modal-close:hover {
  background-color: #f5f5f5;
  color: #333;
}

.category-modal-body {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .establish-container {
    bottom: 20px;
    right: 20px;
  }

  .main-button {
    width: 50px;
    height: 50px;
    font-size: 20px;
    bottom: 0;
    right: 0;
  }

  .expanded-buttons.show {
    width: 130px;
  }

  .action-button {
    min-width: 100px;
    padding: 8px 12px;
  }

  .action-button span {
    font-size: 12px;
  }
}
</style>