<template>
  <div class="knowledge-config">
    <div class="config-header" @click="togglePanel">
      <img src="../../assets/svg/book.svg" alt="knowledge" class="config-icon" />
      <span>知识库配置</span>
      <img
        :src="isPanelOpen ? upIcon : downIcon"
        alt="toggle"
        class="toggle-icon"
      />
    </div>
    
    <div v-show="isPanelOpen" class="config-panel">
      <div class="knowledge-list">
        <div class="knowledge-group" v-for="group in knowledgeGroups" :key="group.label">
          <div class="group-header">{{ group.label }}</div>
          <div class="checkbox-list">
            <a-checkbox-group v-model:value="selectedKnowledge[group.key]">
              <div v-for="item in group.items" :key="item.value" class="checkbox-item">
                <a-checkbox :value="item.value">
                  {{ item.label }}
                  <span class="item-desc">{{ item.description }}</span>
                </a-checkbox>
              </div>
            </a-checkbox-group>
          </div>
        </div>
      </div>

      <div class="action-buttons">
        <a-button type="primary" :loading="saving" @click="saveConfig">
          保存配置
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import upIcon from '@/assets/svg/ups.svg';
import downIcon from '@/assets/svg/down.svg';

// 将 KNOWLEDGE_GROUPS 改为响应式数据
const knowledgeGroups = ref([]);
const isPanelOpen = ref(false);
const saving = ref(false);

// 用于存储每个分组的选中状态
const selectedKnowledge = reactive({
  product: [],
  tech: [],
  industry: []
});

const togglePanel = () => {
  isPanelOpen.value = !isPanelOpen.value;
};

const saveConfig = async () => {
  saving.value = true;
  try {
    // 保存配置到 localStorage
    localStorage.setItem('knowledgeConfig', JSON.stringify(selectedKnowledge));
    message.success('知识库配置保存成功');
  } catch (error) {
    message.error('知识库配置保存失败');
  } finally {
    saving.value = false;
  }
};

// 初始化配置
const initConfig = () => {
  const savedConfig = localStorage.getItem('knowledgeConfig');
  if (savedConfig) {
    const config = JSON.parse(savedConfig);
    Object.keys(config).forEach(key => {
      selectedKnowledge[key] = config[key];
    });
  }
};

// 添加获取知识库子项的方法
const fetchKnowledgeItems = async (kbId) => {
  try {
    // 方案1：使用 URLSearchParams
    const params = new URLSearchParams();
    params.append('page', 1);
    params.append('kb_id', kbId);
    params.append('pageSize', 9999);
    
    const response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/docType/selectTypeList`, 
      params,
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      }
    );
    return response.data.data || []; // 假设返回数据在 records 字段中，根据实际调整
  } catch (error) {
    console.error('获取知识库子项失败:', error);
    return [];
  }
};

// 修改获取知识库信息的方法
const fetchKnowledgeGroups = async () => {
  try {
    const userId = 2;
    const response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/kbm/selectBucketInfo`, {
      user_id: userId
    },
    {
      headers: {
        'Authorization': `JWT ${localStorage.getItem('token')}`
      }
    }
    );
    
    // 获取每个知识库的子项
    const groupsWithItems = await Promise.all(
      response.data.data.map(async (group) => {
        const items = await fetchKnowledgeItems(group.id);
        console.log(items);
        return {
          label: group.name,
          key: group.id,
          items: items.map(item => ({
            label: item.name,
            value: item.id,
           /*  description: item.desc */
          }))
        };
      })
    );
    
    knowledgeGroups.value = groupsWithItems;
    
    // 初始化选中状态对象
    knowledgeGroups.value.forEach(group => {
      if (!selectedKnowledge[group.key]) {
        selectedKnowledge[group.key] = [];
      }
    });
  } catch (error) {
    message.error('获取知识库信息失败');
    console.error('获取知识库信息失败:', error);
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchKnowledgeGroups();
  initConfig(); // 在获取数据后再初始化配置
});
</script>

<style scoped>
.knowledge-config {
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  background: var(--secondary-bg);
  color: var(--primary-text);
}

.config-header {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.config-header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.config-icon {
  width: 16px;
  height: 16px;
}

.toggle-icon {
  width: 12px;
  height: 12px;
  margin-left: auto;
}

.config-panel {
  padding: 12px 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.knowledge-list {
  margin-bottom: 16px;
}

.knowledge-group {
  margin-bottom: 16px;
}

.knowledge-group:last-child {
  margin-bottom: 0;
}

.group-header {
  font-size: 13px;
  color: var(--primary-text);
  margin-bottom: 8px;
}

.checkbox-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.checkbox-item {
  display: flex;
  align-items: flex-start;
}

.item-desc {
  margin-left: 8px;
  font-size: 12px;
  color: var(--primary-text);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.ant-checkbox-wrapper) {
  font-size: 14px;
}

:deep(.ant-checkbox-group) {
  width: 100%;
  flex-direction: column;
}

:deep(.ant-checkbox-wrapper + .ant-checkbox-wrapper) {
  margin-left: 0;
}
</style> 