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

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';
import TinymceEditor from '#/components/tinymce/src/editor.vue';
import { ElUpload, ElIcon} from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

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

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

const isUpdateRef = ref<boolean>(false);
const isViewRef = ref<boolean>(false);
const isCopyRef = ref<boolean>(false);

// 附件列表 - 添加类型定义
const attachments = ref<any[]>([]);

// 定义抽屉数据类型
interface DrawerData {
  id?: string;
  taskName?: string;
  isUpdate?: boolean;
  isView?: boolean;
  isCopy?: boolean;
  attachment?: any[];
  [key: string]: any;
}

const formOptions = computed(() => {
  return {
    showDefaultActions: !isViewRef.value,
    schema: drawerFormSchema(),
    isDisabled: isViewRef.value,
  };
});

const [Form, formApi] = useVbenForm(formOptions.value);

const drawerTitle = computed(() => {
  if (isViewRef.value) return '查看任务';
  if (isUpdateRef.value) return '编辑任务';
  if (isCopyRef.value) return '复制任务';
  return '新增任务';
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    
    try {
      drawerApi.drawerLoading(true);
      const data = drawerApi.getData() as DrawerData;
      
      // 更新状态
      isUpdateRef.value = !!data.isUpdate;
      isViewRef.value = !!data.isView;
      isCopyRef.value = !!data.isCopy;
      
      // 更新表单配置
      formApi.setOptions(formOptions.value);
      
      if ((isUpdateRef.value || isViewRef.value) && data.id) {
        // 编辑或查看模式
        await formApi.setValues(data);
        // 设置附件列表
        attachments.value = data.attachment || [];
      } else if (isCopyRef.value) {
        // 复制模式
        await formApi.setValues({
          id: '', 
          taskName: data.taskName ? `${data.taskName}（副本）` : ''
        });
        // 清空附件
        attachments.value = [];
      }
    } catch (error) {
      console.error('获取任务详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      
      const formData = await formApi.getValues();
      
      // 添加附件数据
      if (attachments.value.length > 0) {
        formData.attachment = attachments.value;
      }
      
      console.log('提交数据:', formData);
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存任务信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    // 重置表单和状态
    formApi.resetForm();
    isUpdateRef.value = false;
    isViewRef.value = false;
    isCopyRef.value = false;
    attachments.value = [];
  },
});

// 上传文件处理
const handleUpload = (options: any) => {
  // 这里是模拟上传，实际项目中需要调用真实的上传接口
  console.log('上传文件:', options.file);
  
  // 模拟上传成功响应
  const mockResponse = {
    code: 200,
    data: {
      url: URL.createObjectURL(options.file),
      name: options.file.name,
      size: options.file.size,
      type: options.file.type,
    },
    message: '上传成功',
  };
  
  // 调用成功回调
  options.onSuccess(mockResponse, options.file, []);
};

// 移除文件处理
const handleRemove = (file: any, fileList: any[]) => {
  console.log('移除文件:', file);
  attachments.value = fileList;
};

// 预览文件处理
const handlePreview = (file: any) => {
  console.log('预览文件:', file);
  // 这里可以实现文件预览功能
};
</script>

<template>
  <Drawer :title="drawerTitle">
    <Form>
      <!-- 自定义Tinymce编辑器插槽 -->
      <template #taskDescription="scope">
        <TinymceEditor v-model="scope.modelValue" :height="400" />
      </template>

      <!-- 自定义附件上传插槽 -->
      <template #attachment="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"
          :http-request="handleUpload"
          :on-remove="handleRemove"
          :on-preview="handlePreview"
          class="task-attachment-upload"
        >
          <div class="upload-container">
            <div class="upload-icon">
              <ElIcon>
                <Plus size="40" />
              </ElIcon>
            </div>
            <div class="upload-content">
              <div class="upload-title">点击上传文件</div>
              <div class="upload-desc">或拖拽文件到此处</div>
              <div class="upload-tip">
                <span class="tip-limit">最多可上传5个文件</span>
                <span class="tip-types">支持格式：图片、PDF、Word、Excel、PPT</span>
              </div>
            </div>
          </div>
        </ElUpload>
      </template>
    </Form>
  </Drawer>
</template>

<style scoped>
.task-attachment-upload {
  width: 100%;
}

.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;
  background-color: #fafafa;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  transition: all 0.3s;
}

.upload-container:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.upload-icon {
  margin-bottom: 15px;
  color: #409eff;
}

.upload-content {
  text-align: center;
}

.upload-title {
  margin-bottom: 5px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.upload-desc {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.upload-tip {
  display: flex;
  flex-direction: column;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.tip-limit, .tip-types {
  display: inline-block;
}
</style>
