<script setup lang="ts">
import { ref } from 'vue';
import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import { UploadFilled, Plus } from '@element-plus/icons-vue';
import { ElUpload } from 'element-plus';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { drawerFormSchema } from './config-data';

const emit = defineEmits<{
  reload: [];
}>();

// 模拟API调用，实际项目中需要替换为真实API
const addKnowledgeType = async (data: any) => {
  console.log('添加知识库类型', data);
  return { success: true };
};

const updateKnowledgeType = async (data: any) => {
  console.log('更新知识库类型', data);
  return { success: true };
};

const getKnowledgeTypeDetail = async (id: string) => {
  console.log('获取知识库类型详情', id);
  // 模拟数据
  return {
    id,
    name: '测试类型',
    description: '测试描述',
    icon: 'carbon:test',
    admin: 'admin',
    applicableEnd: 'pc',
    applicablePost: 'admin',
  };
};

// 默认图标列表
const defaultIcons = [
  { label: '产品知识', value: 'carbon:product' },
  { label: '技术文档', value: 'carbon:code' },
  { label: '常见问题', value: 'carbon:question' },
];

// 图标文件列表
const iconFileList = ref([]);

// 可选图标列表，使用public/icon下的本地图片
const optionalIcons = [
  { label: '文档', value: '/icon/1.png' },
  { label: '代码', value: '/icon/2.png' },
  { label: '问题', value: '/icon/3.png' },
  { label: '书籍', value: '/icon/4.png' }
];

// 上传请求处理
const handleUpload = (options) => {
  console.log('上传图标', options);
  // 实际项目中需要调用上传API
  // 这里模拟上传成功
  const mockResponse = {
    data: {
      url: URL.createObjectURL(options.file),
      filename: options.file.name,
    },
  };
  // 更新文件列表
  scope.icon = [
    {
      name: options.file.name,
      url: mockResponse.data.url,
      status: 'success',
      uid: options.file.uid,
    },
  ];
  // 更新表单值
  formApi.setValues({ icon: mockResponse.data.url });
  options.onSuccess(mockResponse);
};

// 移除文件处理
const handleRemove = (file, fileList) => {
  console.log('移除图标', file, fileList);
  scope.icon = fileList;
  if (fileList.length === 0) {
    formApi.setValues({ icon: '' });
  }
};

// 预览文件处理
const handlePreview = (file) => {
  console.log('预览图标', file);
  // 实际项目中可以实现预览功能
};

// 选择可选图标
const selectOptionalIcon = (iconValue, currentScope) => {
  console.log('选择可选图标', iconValue, currentScope);
  // 生成一个模拟的文件对象
  const mockFile = {
    name: `${iconValue.replace('carbon:', '')}.svg`,
    url: iconValue,
    status: 'success',
    uid: Date.now(),
    isOptional: true,
  };
  // 更新文件列表
  currentScope.icon = [mockFile];
  // 更新表单值
  formApi.setValues({ icon: iconValue });
};

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

const isUpdateRef = ref<boolean>(false);

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate && id) {
        const res = await getKnowledgeTypeDetail(id);
        console.log('获取知识库类型详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;
        await formApi.setValues(detailData);
      } else {
        // 新增时重置表单
        await formApi.resetForm();
      }
    } catch (error) {
      console.error('获取知识库类型详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();

      console.log('提交数据:', data);
      await (isUpdateRef.value
        ? updateKnowledgeType(data)
        : addKnowledgeType(data));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存知识库类型失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },
});

// 暴露drawerApi给父组件
defineExpose({
  getDrawerApi: () => drawerApi,
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑知识库分类' : '新增知识库分类'">
    <Form>
      <!-- 自定义Upload组件插槽 -->
      <template #icon="scope">
        <div class="flex items-start gap-6">
          <!-- 上传组件 -->
          <ElUpload
            v-model:file-list="scope.icon"
            action="#"
            accept=".jpg,.jpeg,.png"
            list-type="picture-card"
            show-file-list
            :auto-upload="true"
            :drag="false"
            :http-request="handleUpload"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            class="w-[60px] h-[60px]"
            :style="{ width: '60px', height: '60px' }"
          >
            <div class="w-full h-full flex items-center justify-center">
              <ElIcon class="el-upload__icon">
                <Plus size="18" />
              </ElIcon>
            </div>
          </ElUpload>
          
          <!-- 可选图标列表 -->
          <div class="flex flex-col gap-2">
            <div class="text-xs text-gray-500">可选图标：</div>
            <div class="flex gap-3 flex-wrap">
              <div 
                v-for="icon in optionalIcons" 
                :key="icon.value"
                class="optional-icon-item"
                @click="selectOptionalIcon(icon.value, scope)"
              >
                <img :src="icon.value" :alt="icon.label" class="w-10 h-10" />
              </div>
            </div>
          </div>
        </div>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped lang="scss">
.optional-icon-item {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f5f7fa;
  
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
    transform: scale(1.1);
  }
  
  &:active {
    transform: scale(0.9);
  }
}

::v-deep .el-upload--picture-card {
    --el-upload-picture-card-size: 148px;
    align-items: center;
    background-color: #fafafa;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed #cdd0d6;
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-flex;
    height: 60px;
    justify-content: center;
    vertical-align: top;
    width: 60px;
}
</style>
