<template>
    <div class="history-container-page">
      <!-- 左侧类型选择 -->
      <!-- <div class="left-panel">
        <el-select v-model="currentType" placeholder="选择历史类型" class="type-select">
          <el-option label="全部" value="all" />
          <el-option label="对话" value="chat" />
          <el-option label="方案" value="solution" />
          <el-option label="文档" value="doc" />
        </el-select>
      </div> -->
  
      <!-- 右侧内容区 -->
      <div class="right-panel">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
          <div class="search-container">
            <div class="back-btn" @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              <span>历史记录</span>
            </div>
            <el-input
              v-model="searchText"
              placeholder="搜索历史..."
              clearable
              class="search-input"
              @keyup="handleSearchKeyup"
            >
              <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="type-buttons">
          <el-button 
            v-for="type in typeOptions" 
            :key="type.value"
            :type="currentType === type.value ? 'primary' : ''"
            @click="currentType = type.value"
            class="type-btn"
          >
            {{ type.label }}
          </el-button>
        </div>
  
        <!-- 历史列表 -->
        <div class="history-list" v-loading="loading">
          <template v-if="filteredHistory.length">
            <div
              v-for="item in filteredHistory"
              :key="item.id"
              class="favorite-item"
              :class="{'file-download': item.relatedType === 'file.download'}"
            >
              <div class="item-content" @click="handleItemClick(item)">
                <el-checkbox 
                  v-show="isBatchMode"
                  v-model="item.checked"
                  @change="handleItemSelect"
                  @click.stop
                />
                <div class="item-title">{{ item.relatedType==='ai.answer'? item.askContent : 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, ArrowLeft } from '@element-plus/icons-vue'
  import { get, post, del ,put} from '../utils/request'
  import { useRouter } from 'vue-router'
  import { downloadFile } from '../utils'
  
  // 将状态变量的声明移到最前面
  const searchText = ref('')
  const currentType = ref('all')
  const loading = ref(false)
  const history = 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 filteredHistory.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 filteredHistory = computed(() => {
    let result = history.value.map(item => ({
      ...item,
      checked: item.checked || false
    }))
  
    // 类型过滤
    if (currentType.value !== 'all') {
      result = result.filter(item => item.relatedType === currentType.value)
    }
  
    // 搜索过滤
    if (searchText.value) {
      const searchLower = searchText.value.toLowerCase()
      result = result.filter(item => 
        item.title?.toLowerCase().includes(searchLower)
      )
    }
  
    return result
  })
  
  // 获取历史列表
  const fetchHistory = 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/userHistoryLog/pageList', params)
      // console.log('response.rows', response.data.rows);
      history.value = response.data.rows || []
      // console.log('history.value', history.value);
      total.value = Number(response.data.total) || 0
    } catch (error) {
      ElMessage.error('获取列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 批量管理相关方法
  const toggleBatchMode = () => {
    isBatchMode.value = !isBatchMode.value
    isAllSelected.value = false
    history.value = history.value.map(item => ({
      ...item,
      checked: false
    }))
  }
  
  const cancelBatchMode = () => {
    isBatchMode.value = false
    isAllSelected.value = false
    history.value = history.value.map(item => ({
      ...item,
      checked: false
    }))
  }
  
  const handleSelectAll = (val) => {
    history.value = history.value.map(item => ({
      ...item,
      checked: val
    }))
    isAllSelected.value = val
  }
  
  const handleItemSelect = () => {
    // 检查当前过滤后的列表是否全部选中
    isAllSelected.value = filteredHistory.value.length > 0 && 
      filteredHistory.value.every(item => item.checked)
  }
  
  const handleBatchDelete = async () => {
    try {
      await ElMessageBox.confirm(
        '确定要删除选中的历史吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      const selectedIds = history.value
        .filter(item => item.checked)
        .map(item => item.id)
      
      if (selectedIds.length === 0) {
        ElMessage.warning('请选择要删除的项')
        return
      }
      
      await post('/history/batch-delete', { ids: selectedIds })
      ElMessage.success('删除成功')
      await fetchHistory()
      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('/history/rename', renameForm.value)
      
      ElMessage.success('重命名成功')
      renameDialogVisible.value = false
      fetchHistory()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('重命名失败')
      }
    }
  }
  
  const removeFavorite = async (item) => {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个历史吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      await put('admin/userCollect/cancel', {
        id: item.collectId,
        relatedType: 'file.download',//related_type : AI问答 : ai.answer 方案:scheme 文件检索: file.search
        relatedId: item.id,
      })
      ElMessage.success('删除成功')
      fetchHistory()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
  
  // 工具函数
  const getTagType = (type) => {
    const types = {
      'ai.answer': 'success',
      scheme: 'success',
      doc: 'warning',
      'file.download': 'success',
      'file.search': 'warning'
    }
    return types[type] || 'info'
  }
  
  const getTypeLabel = (type) => {
    const labels = {
      'ai.answer': 'AI对话',
      scheme: '方案生成',
      doc: '文档',
      'file.download': '下载文件',
      'file.search': '文件检索'
    }
    return labels[type] || '未知'
  }
  
  const formatDate = (date) => {
    return new Date(date).toLocaleString()
  }
  
  const getEmptyText = () => {
    // console.log('currentType.value', currentType.value);
    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 fetchHistory()
    } finally {
      searchLoading.value = false
    }
  }
  
  // 监听搜索框回车事件
  const handleSearchKeyup = (e) => {
    if (e.key === 'Enter') {
      handleSearch()
    }
  }
  
  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1 // 切换每页条数时重置为第一页
    fetchHistory()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchHistory()
  }
  
  // 监听类型变化
  watch(currentType, () => {
    currentPage.value = 1 // 切换类型时重置为第一页
    fetchHistory()
  })
  
  // 类型选择相关
  const typeOptions = [
    { label: '全部', value: 'all' },
    { label: 'AI对话', value: 'ai.answer' },
    { label: '方案生成', value: 'scheme' },
    { label: '下载文件', value: 'file.download' }
  ]
  
  const router = useRouter()
  
  const goBack = () => {
    router.back()
  }
  
  const handleItemClick = async (item) => {
    if (!item.relatedType) return;

    switch (item.relatedType) {
      case 'ai.answer':
        // router.push(`/ai-chat?historyId=${item.id}`);
        window.location.href = `/ai-chat?historyId=${item.id}`
        break;
      case 'scheme':
        router.push(`/solution?historyId=${item.id}`);
        break;
      case 'file.download':
        try {
          // console.log('item.fileName',item.fileName);
          await downloadFile(item.fileUrl, item.fileName)
          // 添加文件下载记录
          await post('/admin/userHistoryLog/saveFileDownloadLog', {
            relatedId: item.relatedId
          })
        } catch (error) {
          console.log('error', error)
          ElMessage.error('下载失败，请重试文件地址:'+item.fileUrl)
        }
        // try {
        //   // 调用下载接口
        //   const response = await get(`admin/file/download/${item.id}`, {}, {
        //     responseType: 'blob'
        //   });
          
        //   // 创建下载链接
        //   const blob = new Blob([response], { type: response.type });
        //   const url = window.URL.createObjectURL(blob);
        //   const link = document.createElement('a');
        //   link.href = url;
        //   link.download = item.fileName || '下载文件';
        //   document.body.appendChild(link);
        //   link.click();
        //   document.body.removeChild(link);
        //   window.URL.revokeObjectURL(url);
        // } catch (error) {
        //   ElMessage.error('文件下载失败');
        // }
        break;
        case 'file.search':
        try {
          await downloadFile(item.fileUrl, item.fileName)
          // 添加文件下载记录
          await post('/admin/userHistoryLog/saveFileDownloadLog', {
            relatedId: item.relatedId
          })
        } catch (error) {
          console.log('error', error)
          ElMessage.error('下载失败，请重试文件地址:'+item.fileUrl)
        }
        break;
      default:
        break;
    }
  };
  
  // 初始化
  fetchHistory()
  </script>
  
  <style lang="scss" scoped>
  .history-container-page {
    height: 100%;
    display: flex;
    flex-direction: row;
    gap: 0;
    padding: 0 15%;
  }
  
  .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;
      
      .back-btn {
        display: flex;
        align-items: center;
        cursor: pointer;
        margin-right: 20px;
        color: #333;
        
        .el-icon {
          margin-right: 8px;
          font-size: 16px;
        }
        
        span {
          font-size: 16px;
          font-weight: 500;
        }
        
        &:hover {
          color: var(--el-color-primary);
        }
      }

      .el-input {
        height: 50px;
        width: 60%;
        margin-left: 20%;
      }
    }
      
      .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;
        }
      }
  
  }
  
  .history-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;
    }
  }
  
  .type-buttons {
    padding: $spacing-base;
    background-color: $background-white;
    border-radius: $border-radius-base;
    display: flex;
    gap: $spacing-base;
    margin-bottom: $spacing-base;

    .type-btn {
      flex: 1;
      max-width: 110px;
      height: 40px;
      border-radius: 20px;
      border: none;
      background: #F4F5F8;
      color: #8B8C90;
      
      &.el-button--primary {
        background: #FFFFFF;
        box-shadow: 0px 1px 8px 0px rgba(192,202,209,0.5);
        color: #31333C;
      }
    }
  }
  </style> 