<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { ElButton, ElCard, ElIcon, ElPagination } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import KnowledgeCreate from './create.vue';
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import {
  addKnowledgeCategory,
  queryKnowledgeCategory,
  editKnowledgeCategory,
  deleteKnowledgeCategory,
} from '#/api/knowledge/category';
// import '../../../../public/iconfonts/font/iconfont.css';

// 导入 FormData 类型
interface FormData {
  id?: number;
  name: string;
  description: string;
  icon: string;
  managers: any[];
  visibleApps: any[];
  visiblePositions: any[];
  association: string;
}

// 路由实例
const router = useRouter();
// 抽屉加载状态
const loading = ref(false);
// 示例数据
const categories = ref([]) as any;
const total = ref<number>(0);
const currentPage = ref(1);
const pageSize = ref<number>(15);
const createCategory = async () => {
  try {
    const res = await queryKnowledgeCategory({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    console.log(res);

    // if (res.code === 200) {
    categories.value = res.rows || [];
    total.value = res.total || 0;
    // }
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  createCategory();
});
// 抽屉控制
const drawerVisible = ref(false);
const drawerMode = ref('create');
const selectedCategory = ref<FormData>({
  name: '',
  description: '',
  icon: '',
  managers: [],
  visibleApps: [],
  visiblePositions: [],
  association: '',
}) as any;

// 跳转到详情页
const navigateToDetail = (id: number) => {
  const category = categories.value.find((item: any) => item.id === id);
  const cleaned = category?.icon?.replace(/#/g, '');
  // console.log(cleaned);
  if (cleaned.includes('iconfont')) {
    router.push(`/knowledge/detail/${id}/${category.name}/${cleaned}`);
  } else {
    const iconUrl = category?.iconUrl?.[0] || '';
    router.push(
      `/knowledge/detail/${id}/${category.name}/${encodeURIComponent(iconUrl)}`,
    );
  }
};

// 打开创建抽屉
const openCreateDrawer = () => {
  drawerMode.value = 'create';
  selectedCategory.value = {
    name: '',
    description: '',
    icon: '',
    managers: [],
    visibleApps: [],
    visiblePositions: [],
    association: '',
  };
  drawerVisible.value = true;
};

// 打开编辑抽屉
const openEditDrawer = (category: any) => {
  console.log(category);

  drawerMode.value = 'edit';
  selectedCategory.value = {
    id: category.id || '',
    name: category.name || '',
    description: category.description || '',
    icon:
      category?.icon !== '' && category?.icon?.includes('iconfont')
        ? category.icon
        : category?.iconUrl?.[0] || '',
    managers: [],
    visibleApps: [],
    visiblePositions: [],
    association: category.associationIds || '',
  };
  drawerVisible.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
};

// 保存知识类别
const saveCategory = async (data: any) => {
  loading.value = true;
  if (drawerMode.value === 'create') {
    // 这里可以添加创建逻辑
    try {
      await addKnowledgeCategory({
        ...data,
        // category.icon !== '' && category.icon.includes('iconfont')
        // ? category.icon
        // : category.iconUrl[0] || '',
        icon:
          data?.icon !== '' && data?.icon?.includes('iconfont')
            ? data.icon
            : data?.upiconname || '',
        associationIds: data?.association || '',
      });
      await createCategory();
      closeDrawer();
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  } else {
    // 这里可以添加编辑逻辑
    try {
      await editKnowledgeCategory({
        ...data,
        icon:
          data?.icon !== '' && data?.icon?.includes('iconfont')
            ? data.icon
            : data?.upiconname || '',
        associationIds: data?.association || '',
      });
      await createCategory();
      closeDrawer();
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  }
};
const deleteCategory = async (id: any) => {
  try {
    await deleteKnowledgeCategory(id);
    await createCategory();
  } catch (error) {
    console.log(error);
  }
};
</script>
<template>
  <Page>
    <div class="wrap">
      <!-- 页面头部 -->
      <div class="header">
        <ElButton type="primary" @click="openCreateDrawer"
          >+ 创建知识库</ElButton
        >
        <!-- <ElButton type="default">管理</ElButton> -->
      </div>
      <!-- 卡片列表 -->
      <div class="card-list">
        <div
          v-for="category in categories"
          :key="category.id"
          class="card-item"
        >
          <ElCard
            :bordered="false"
            class="category-card"
            @click="navigateToDetail(category.id)"
          >
            <div class="card-content">
              <!-- 左侧图标 -->
              <div
                class="card-icon"
                :style="{
                  backgroundColor: category.color + '20',
                  color: category.color,
                }"
              >
                <!-- <ElIcon :icon="category.icon" size="24" /> -->
                <span
                  v-if="category?.icon?.includes('iconfont')"
                  :class="category?.icon?.split(',')[0]"
                  :style="{
                    color: category?.icon?.split(',')[1],
                    fontSize: '30px',
                  }"
                ></span>
                <img v-else :src="category?.iconUrl?.[0] || ''" alt="" />
              </div>
              <!-- 中间内容 -->
              <div class="card-main">
                <h3 class="card-title">{{ category.name }}</h3>
                <p class="card-description">{{ category.description }}</p>
              </div>
              <!-- 右侧信息 -->
              <div class="card-info">
                <div class="creator">{{ category.createBy }}</div>
                <div class="create-time">{{ category.createTime }}</div>
                <!-- 操作按钮 -->
                <div class="card-actions">
                  <ElButton
                    type="text"
                    :icon="Edit"
                    circle
                    @click.stop="openEditDrawer(category)"
                  />
                  <ElButton
                    type="text"
                    :icon="Delete"
                    circle
                    @click.stop="deleteCategory(category.id)"
                  />
                </div>
              </div>
            </div>
          </ElCard>
        </div>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <ElPagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="createCategory"
        />
      </div>
      <!-- 创建/编辑抽屉 -->
      <ElDrawer
        v-model="drawerVisible"
        :title="drawerMode === 'create' ? '创建知识库' : '编辑知识库'"
        size="30%"
        direction="rtl"
        @close="closeDrawer"
      >
        <KnowledgeCreate
          v-loading="loading"
          :mode="drawerMode"
          :initial-data="selectedCategory"
          @close="closeDrawer"
          @save="saveCategory"
        />
      </ElDrawer>
    </div>
  </Page>
</template>
<style lang="scss" scoped>
.wrap {
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
}

.header {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.card-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.category-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-card:hover {
  background-color: #e8f3ff;
}

.category-card:hover .card-title {
  color: #2d64d0;
}

.category-card:hover .creator,
.category-card:hover .create-time {
  display: none;
}

.category-card:hover .card-actions {
  display: flex;
}

.card-content {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 10px 0;
}

.card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border-radius: 6px;
}

.card-main {
  flex: 1;
  min-width: 0;
}

.card-title {
  margin: 0 0 4px;
  overflow: hidden;
  font-size: 16px;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s ease;
}

.card-description {
  margin: 0;
  overflow: hidden;
  font-size: 12px;
  color: #666;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-info {
  min-width: 80px;
  text-align: right;
}

.creator {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.create-time {
  font-size: 12px;
  color: #999;
}

.card-actions {
  display: none;
  gap: 8px;
  justify-content: flex-end;
}

.pagination {
  display: flex;
  justify-content: center;
}
</style>
