<template>
  <div class="app-wrapper">
    <!-- 侧边栏 -->
    <div class="sidebar-container" :class="{ 'is-collapse': userStore.isCollapse }">
      <!-- 顶部logo -->
      <div class="logo-container" @click="userStore.toggleCollapse">
        <img src="../assets/logo.png" alt="logo" class="logo">
        <span class="name" v-show="!userStore.isCollapse">省信息中心</span>
        <img src="../assets/toggle-icon.png" alt="toggle" class="toggle-icon" v-show="!userStore.isCollapse"/>
      </div>
      
      <!-- 菜单 -->
       <div class="menu-container">
      <el-menu
        :collapse="userStore.isCollapse"
        :default-active="route.path"
        class="sidebar-menu"
        router
      >
        <el-menu-item index="/new-chat" @click="handleNewChat">
          <img src="../assets/newchat.png" alt="newchat"/>
          <template #title>新建对话</template>
        </el-menu-item>
        
        <el-menu-item index="/ai-chat">
          <img src="../assets/ChatLineRound.png" alt="chat"/>
          <template #title>AI对话</template>
        </el-menu-item>
        
        <!-- <el-menu-item index="/solution">
          <img src="../assets/Document.png" alt="solution"/>
          <template #title>方案生成</template>
        </el-menu-item> -->
        
        <el-menu-item index="/doc-search">
          <img src="../assets/Search.png" alt="search"/>
          <template #title>文档搜索</template>
        </el-menu-item>
        
        <el-menu-item index="/favorites">
          <img src="../assets/Star.png" alt="favorites"/>
          <template #title>收藏夹</template>
        </el-menu-item>
        <el-menu-item index="/history" v-if="userStore.isCollapse">
          <img src="../assets/history.png" alt="history"/>
          <template #title>历史记录</template>
        </el-menu-item>
      </el-menu>
      </div>
      <!-- 历史记录 -->
      <div class="history-container" v-show="!userStore.isCollapse&&historyList.length>0">
        <div class="history-title">
          <img src="../assets/history.png" alt="history"/>
          历史记录
        </div>
        <div class="history-list">
          <div v-for="(item, index) in historyList" 
               :key="index" 
               class="history-item"
               @click="handleHistoryClick(item)">
            {{ item.fileName||item.askContent }}
          </div>
          <!-- v-if="hasMore" -->
          <div 
               class="view-more"
               @click="handleViewMore">
            查看更多
            <img src="../assets/icon-more.png" alt="icon-more"/>
          </div>
        </div>
      </div>
      
      <!-- 用户信息 -->
      <div class="user-container" @click="router.push('/user-info')">
        <el-avatar :size="40" :src="userStore.userInfo.headUrl"/>
        <div v-show="!userStore.isCollapse" class="user-info">
          <div class="username">{{ userStore.userInfo.realName||userStore.userInfo.username }}</div>
          <div class="phone">{{ hidePhoneNumber(userStore.userInfo.mobile) }}</div>
        </div>
        <!-- <div v-show="!userStore.isCollapse" class="rank">
          <span class="rank-number">{{ userStore.userInfo.rank||'100' }}</span>
          <span class="rank-text">使用排名</span>
        </div> -->
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="main-container">
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import request from '../utils/request' // 确保引入request
import { ElMessage } from 'element-plus'
import { get, post,put } from '../utils/request'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 修改历史记录为响应式数据
const historyList = ref([])
const hasMore = ref(false)

// 获取历史记录数据
const getHistoryList = async () => {
  try {
    const res = await request({
      url: 'admin/userHistoryLog/pageList',
      method: 'get',
      params: {
        pageNum: 1,
        pageSize: 5
      }
    })
    // console.log('res', res);
    
    if (res.data.rows) {
      historyList.value = res.data.rows || []
      hasMore.value = res.data.total > 5
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
  }
}

// 组件挂载时获取历史记录
onMounted(() => {
  getHistoryList()
})

const handleHistoryClick = async (item) => {
  // 处理历史记录点击
  console.log('点击历史记录:', item)
  console.log('item.relatedType',item.relatedType);
  console.log('item.relatedType',item.relatedType=='ai.answer');
  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 {
          window.open(item.fileUrl, '_blank')
          // 添加文件下载记录
          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;
      default:
        break;
    }
}

const handleViewMore = () => {
  router.push('/history')
}

// 手机号码中间4位变星星
const hidePhoneNumber = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

const handleNewChat = () => {
  // router.push('/ai-chat')
  window.location.href = '/ai-chat'
}
</script>

<style lang="scss" scoped>
.app-wrapper {
  display: flex;
  height: 100vh;
  width: 100%;
  &:has(.chat-container){
    .sidebar-container{
      margin-right: 0;
    }
  }
}

.sidebar-container {
  width: $sidebar-width;
  height: 100%;
  background-color: #fff;
  transition: width 0.3s;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  
  &.is-collapse {
    width: $sidebar-collapsed-width;
    
    .logo-container span {
      display: none;
    }
    .menu-container{
      padding: 0;
    }
    .user-container{
      margin: 0;
    }
  }
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 $spacing-base;
  color: #333;
  cursor: pointer;
  margin-top: 20px;
  margin-bottom: 5px;
  
  .logo {
    width: 32px;
    height: 32px;
    margin-right: $spacing-base;
  }
  .name{
    font-weight: bold;
    font-size: 20px;
    color: #1B2343;
    white-space: nowrap;
  }
  
  .toggle-icon {
    margin-left: auto;
    width: 20px;
    height: 20px;
  }
}

.menu-container{
  padding: 0 $spacing-base;
}
.sidebar-menu {
  border: none;
  background-color: transparent;
  :deep(.el-menu-item) {
    display: flex;
    align-items: center;
    color: #333;
    border-radius: 16px;
    font-size: 16px;
    font-weight: bold;
    border: 1px solid transparent;
    img {
      width: 20px;
      height: 20px;
      margin-right: 8px;
    }
    
    &.is-active {
      background-color: #FFECEC;
      border: 1px solid #F9C9C9;
    }
    &:hover{
      background-color: #FFECEC;
      // border: 1px solid #F9C9C9;
    }
  }
}

.history-container {
  flex: 1;
  padding: $spacing-base;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  
  .history-title {
    border-top:1px solid #DCDCDD;
    padding-top: 15px;
    color: $sidebar-text;
    margin-bottom: $spacing-base;
    font-size: 16px;
    font-weight: bold;
    display: flex;
    align-items: center;
    img{
      width: 20px;
      height: 20px;
      margin-right: 8px;
    }
  }
  
  .history-item {
    color: $sidebar-text;
    padding: $spacing-mini $spacing-small;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-weight: 400;
    font-size: 14px;
    color: #373737;
    line-height: 27px;
    font-style: normal;
    
    &:hover {
      color: $sidebar-active-text;
      background-color: rgba(255, 255, 255, 0.05);
    }
  }
  
  .view-more {
    color: $primary-color;
    font-size: 14px;
    cursor: pointer;
    text-align: center;
    margin-top: $spacing-small;
    display: flex;
    align-items: center;
    background-color: $background-color;
    border-radius: 10px;
    padding: 11px 15px;
    width: fit-content;
    img{
      width: 16px;
      height: 16px;
      margin-left: 4px;
    }
  }
}

.user-container {
  margin: $spacing-base;
  padding: 20px 10px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  background: #F8F8FA;
  border-radius: 16px;
  cursor: pointer;
  
  .user-info {
    margin-left: 10px;
    color: $sidebar-text;
    
    font-size: 12px;
    
    .username {
      font-weight: 500;
      font-size: 17px;
      color: #373737;
      line-height: 26px;
      margin-bottom: 4px;
    }
    
    .phone{
      color: #99999B;
    }
  }
  .rank{
    display: flex;
    align-items: center;
    flex-direction: column;
    margin-left: auto;
    .rank-number{
      font-weight: bold;
      font-size: 18px;
      color: #E62222;
    }
    .rank-text{
      font-size: 14px;
      color: #373737;
    }
  }
}

.main-container {
  flex: 1;
  overflow: hidden;
}
</style> 