<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { Plus } from '@element-plus/icons-vue';
import { ElIcon, ElUpload } from 'element-plus';

import TinymceEditor from '#/components/tinymce/src/editor.vue';

import { drawerFormSchema } from './config-data';

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

// 附件列表
const attachments = ref<any[]>([]);
const uploadUrlRef = ref<string>('');

// 表单配置
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 处理附件上传
function handleAttachmentUpload(options: any): Promise<unknown> {
  return new Promise((resolve) => {
    // 模拟上传成功处理
    const fileData = {
      uid: options.file.uid,
      name: options.file.name,
      url: URL.createObjectURL(options.file),
      status: 'success',
      raw: options.file,
    };

    // 多个文件上传时，url以逗号隔开
    uploadUrlRef.value = uploadUrlRef.value
      ? `${uploadUrlRef.value},${fileData.url}`
      : fileData.url;

    options.onSuccess(fileData);
    resolve(fileData);
  });
}

// 移除附件
function handleAttachmentRemove(file: any, fileList: any[]) {
  attachments.value = fileList;
  // 更新上传url，移除已删除的文件
  uploadUrlRef.value = fileList
    .filter((item: any) => item.status === 'success')
    .map((item: any) => item.url)
    .join(',');
}

// 预览附件
function handleAttachmentPreview(file: any) {
  console.log('预览附件', file);
  // TODO: 实现附件预览功能
}

// 确认编辑
async function handleConfirm() {
  try {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = await formApi.getValues();

    // 处理附件url，转换为逗号分隔的字符串
    data.attachments = uploadUrlRef.value;

    // 模拟提交数据
    console.log('提交数据:', data);
    // TODO: 实现真实的API调用

    // 提交成功后触发reload事件
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存失败:', error);
  }
}

const isUpdateRef = ref<boolean>(false);

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { chapter, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate && chapter) {
        // 处理附件url，转换为文件列表格式
        const attachmentsList = chapter.attachments
          ? chapter.attachments
              .split(',')
              .map((url: string, index: number) => ({
                uid: Date.now() + index,
                name: url.split('/').pop() || `文件${index + 1}`,
                url,
                status: 'success',
              }))
          : [];

        uploadUrlRef.value = chapter.attachments || '';
        attachments.value = attachmentsList;

        // 设置表单数据
        await formApi.setValues({
          ...chapter,
          content: chapter.content || '',
          attachments: attachmentsList,
        });
      } else {
        // 新增时重置表单
        await formApi.resetForm();
        attachments.value = [];
        uploadUrlRef.value = '';
      }
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },
  async onConfirm() {
    await handleConfirm();
  },
  onClosed() {
    formApi.resetForm();
    attachments.value = [];
    uploadUrlRef.value = '';
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑章节' : '新增章节'">
    <Form>
      <!-- 自定义Tinymce编辑器插槽 -->
      <template #content="scope">
        <TinymceEditor v-model="scope.modelValue" :height="400" />
      </template>

      <!-- 自定义附件上传插槽 -->
      <template #attachments="scope">
        <ElUpload
          v-model:file-list="attachments"
          action="#"
          accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
          list-type="text"
          show-file-list
          :auto-upload="true"
          :drag="false"
          :limit="5"
          :multiple="true"
          :http-request="handleAttachmentUpload"
          :on-remove="handleAttachmentRemove"
          :on-preview="handleAttachmentPreview"
          class="mb-4"
        >
          <div class="flex items-center justify-center">
            <ElIcon class="el-upload__icon">
              <Plus size="18" />
            </ElIcon>
            <div class="el-upload__text">
              <div>上传附件</div>
              <div class="text-xs text-gray-500">最多上传5个附件</div>
            </div>
          </div>
        </ElUpload>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped lang="scss">
/* 自定义样式 */
</style>

