<template>
  <div class="favorites-container">
    <!-- 左侧类型选择 -->
    <div class="left-panel">
      <el-select v-model="currentType" placeholder="选择收藏类型" class="type-select">
        <el-option label="全部" value="all" />
        <!-- <el-option label="对话" value="ai.answer" /> -->
        <!-- <el-option label="方案" value="scheme" /> -->
        <el-option label="文档" value="file.search" />
      </el-select>
    </div>

    <!-- 右侧内容区 -->
    <div class="right-panel">
      <!-- 顶部工具栏 -->
      <div class="toolbar">
        <div class="search-container">
        <el-input
          v-model="searchText"
          placeholder="搜索收藏..."
          clearable
          class="search-input"
          @keyup="handleSearchKeyup"
        >
          <!-- <template #prefix>
            <el-icon><Search /></el-icon>
          </template> -->
          <template #append>
            <el-button type="primary" :loading="searchLoading" @click="handleSearch">
              <el-icon :size="20"><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        </div>
        <!-- <el-button @click="toggleBatchMode" class="batch-btn">
          <img src="@/assets/icon-multi.png" class="btn-icon" />
          批量管理
        </el-button> -->
      </div>

      <!-- 收藏列表 -->
      <div class="favorites-list" v-loading="loading">
        <template v-if="filteredFavorites.length">
          <div
            v-for="item in filteredFavorites"
            :key="item.id"
            class="favorite-item"
          >
            <div class="item-content">
              <el-checkbox 
                v-show="isBatchMode"
                v-model="item.checked"
                @change="handleItemSelect"
              />
              <div class="item-title">{{ item.name||item.fileName }}</div>
              <div class="item-info">
                <span class="item-date">{{ formatDate(item.createTime) }}</span>
                <el-dropdown v-if="!isBatchMode" @command="handleCommand($event, item)">
                  <img src="@/assets/icon-more.svg" class="action-icon" />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- <el-dropdown-item command="rename">重命名</el-dropdown-item> -->
                      <el-dropdown-item command="delete">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </template>
        
        <el-empty
          v-else-if="!loading"
          :description="getEmptyText()"
        />

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 批量操作底栏 -->
        <div class="batch-footer" v-if="isBatchMode">
          <div class="left">
            <el-checkbox
              v-model="isAllSelected"
              @change="handleSelectAll"
            >
              全选
            </el-checkbox>
            <span class="selected-count">已选择 {{ selectedCount }} 项</span>
          </div>
          <div class="right">
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedCount === 0">
              批量删除
            </el-button>
            <el-button @click="cancelBatchMode">取消</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 重命名弹窗 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名"
      width="400px"
    >
      <el-form
        ref="renameFormRef"
        :model="renameForm"
        :rules="renameRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="renameForm.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRename">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { Search, Edit, Delete, Plus } from '@element-plus/icons-vue'
import { get, post, del ,put} from '../utils/request'

// 状态变量
const currentType = ref('all')
const searchText = ref('')
const loading = ref(false)
const favorites = ref([])
const searchLoading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 批量管理相关
const isBatchMode = ref(false)
const isAllSelected = ref(false)
const selectedCount = computed(() => {
  return filteredFavorites.value.filter(item => item.checked).length
})

// 重命名相关
const renameDialogVisible = ref(false)
const renameFormRef = ref(null)
const renameForm = ref({
  id: '',
  title: ''
})

const renameRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性：过滤后的收藏列表
const filteredFavorites = computed(() => {
  let result = favorites.value.map(item => ({
    ...item,
    checked: item.checked || false
  }))

  // 类型过滤
  // if (currentType.value !== 'all') {
  //   result = result.filter(item => item.type === currentType.value)
  // }

  // 搜索过滤
  // if (searchText.value) {
  //   const keyword = searchText.value.toLowerCase()
  //   result = result.filter(item => 
  //     item.name.toLowerCase().includes(keyword)
  //   )
  // }

  return result
})

// 获取收藏列表
const fetchFavorites = async () => {
  loading.value = true
  try {
    const params = {
      relatedType: currentType.value !== 'all' ? currentType.value : undefined,
      searchText: searchText.value.trim() || undefined,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await get('admin/userCollect/pageList', params)
    favorites.value = response.data.rows || []
    total.value = Number(response.data.total) || 0
  } catch (error) {
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 批量管理相关方法
const toggleBatchMode = () => {
  isBatchMode.value = !isBatchMode.value
  isAllSelected.value = false
  favorites.value = favorites.value.map(item => ({
    ...item,
    checked: false
  }))
}

const cancelBatchMode = () => {
  isBatchMode.value = false
  isAllSelected.value = false
  favorites.value = favorites.value.map(item => ({
    ...item,
    checked: false
  }))
}

const handleSelectAll = (val) => {
  favorites.value = favorites.value.map(item => ({
    ...item,
    checked: val
  }))
  isAllSelected.value = val
}

const handleItemSelect = () => {
  // 检查当前过滤后的列表是否全部选中
  isAllSelected.value = filteredFavorites.value.length > 0 && 
    filteredFavorites.value.every(item => item.checked)
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除选中的收藏吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const selectedIds = favorites.value
      .filter(item => item.checked)
      .map(item => item.id)
    
    if (selectedIds.length === 0) {
      ElMessage.warning('请选择要删除的项')
      return
    }
    
    await post('/favorites/batch-delete', { ids: selectedIds })
    ElMessage.success('删除成功')
    await fetchFavorites()
    cancelBatchMode()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 单项操作相关方法
const handleCommand = (command, item) => {
  switch (command) {
    case 'rename':
      showRenameDialog(item)
      break
    case 'delete':
      removeFavorite(item)
      break
  }
}

const showRenameDialog = (item) => {
  renameForm.value = {
    id: item.id,
    title: item.title
  }
  renameDialogVisible.value = true
}

const handleRename = async () => {
  if (!renameFormRef.value) return
  
  try {
    await renameFormRef.value.validate()
    await post('/favorites/rename', renameForm.value)
    
    ElMessage.success('重命名成功')
    renameDialogVisible.value = false
    fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重命名失败')
    }
  }
}

const removeFavorite = async (item) => {
  console.log('item', item);
  try {
    await ElMessageBox.confirm(
      '确定要删除这个收藏吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await del('admin/userCollect/deleteById', {
      id: item.id,
      // relatedType: 'file.search',//related_type : AI问答 : ai.answer 方案:scheme 文件检索: file.search
      // relatedId: item.id,
    })
    // ElMessage.success('删除成功')
    fetchFavorites()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 工具函数
const getTagType = (type) => {
  const types = {
    chat: '',
    solution: 'success',
    doc: 'warning'
  }
  return types[type] || 'info'
}

const getTypeLabel = (type) => {
  const labels = {
    chat: '对话',
    solution: '方案',
    doc: '文档'
  }
  return labels[type] || '未知'
}

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const getEmptyText = () => {
  if (searchText.value) {
    return '未找到匹配的收藏'
  }
  if (currentType.value !== 'all') {
    return `暂无${getTypeLabel(currentType.value)}类型的收藏`
  }
  return '暂无收藏内容'
}

// 搜索相关
const handleSearch = async () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  currentPage.value = 1 // 搜索时重置为第一页
  searchLoading.value = true
  try {
    await fetchFavorites()
  } finally {
    searchLoading.value = false
  }
}

// 监听搜索框回车事件
const handleSearchKeyup = (e) => {
  if (e.key === 'Enter') {
    handleSearch()
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页条数时重置为第一页
  fetchFavorites()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchFavorites()
}

// 监听类型变化
watch(currentType, () => {
  currentPage.value = 1 // 切换类型时重置为第一页
  fetchFavorites()
})

// 初始化
fetchFavorites()
</script>

<style lang="scss" scoped>
.favorites-container {
  height: 100%;
  display: flex;
  flex-direction: row;
  gap: 0;
}

.left-panel {
  width: 300px;
  padding: $spacing-base;
  padding-top: 47px;
  background-color: $background-white;
  border-radius: $border-radius-base;
  .el-select{
    display: flex;
    justify-content: center;
    :deep(.el-select__wrapper){
      height: 50px;
      width: 176px;
      border-radius: 80px;
      background: #FCFCFC;
    }
  }
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: $spacing-base;
  padding-top: 31px;
}

.toolbar {
  padding: $spacing-base;
  background-color: $background-white;
  border-radius: $border-radius-base;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .search-container {
    display: flex;
    align-items: center;
    flex:1;
    margin-right: 90px;
    .el-input{
      height: 50px;
    }
  }
    
    .batch-btn {
      background-color: none;
      color: #fff;
      border: none;
      padding: 8px 16px;
      border-radius: $border-radius-base;
      cursor: pointer;
      transition: background-color 0.3s;
      color:#191A1E;
      
      &:hover {
        background-color: $primary-color;
        color: #fff;
      }
      
      .btn-icon {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }

}

.favorites-list {
  flex: 1;
  overflow-y: auto;
  padding: $spacing-base;
  background-color: $background-white;
  border-radius: $border-radius-base;
}

.favorite-item {
  padding: $spacing-base;
  margin-bottom: 14px;
  background: #F4F5F8;
  border-radius: 12px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .item-content {
    display: flex;
    align-items: center;
    
    .item-title {
      color: $text-primary;
      margin-left: 10px;
      cursor: pointer;
      
      &:hover {
        color: $primary-color;
      }
    }
    
    .item-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-left: auto;
      
      .item-date {
        color: $text-secondary;
        font-size: 12px;
      }
      
      .action-icon {
        width: 16px;
        height: 16px;
        cursor: pointer;
        outline: none;
        margin-left: 10px;
      }
    }
  }
}

.pagination {
  margin-top: $spacing-large;
  display: flex;
  justify-content: center;
}

.edit-tag {
  margin-right: $spacing-mini;
  margin-bottom: $spacing-mini;
}

.button-new-tag {
  margin-bottom: $spacing-mini;
}

.w-120 {
  width: 120px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: $spacing-base;
}

.batch-footer {
  margin-top: 24px;
  padding: $spacing-base;
  background-color: $background-white;
  border-radius: $border-radius-base;
  box-shadow: $box-shadow-light;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .left {
    display: flex;
    align-items: center;
    gap: $spacing-base;
  }
  
  .right {
    display: flex;
    gap: $spacing-base;
  }
}
</style> 