<template>
  <el-dialog
    :model-value="visible"
    title="提交任务进度"
    width="50%"
    @update:model-value="$emit('update:visible', $event)"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" label-width="80px">
      <el-form-item label="进度说明" prop="comments">
        <el-input
          v-model="form.comments"
          type="textarea"
          rows="4"
          placeholder="请输入详细的进度说明..."
        />
      </el-form-item>
      <el-form-item label="上传图片" prop="files">
        <el-upload
          v-model:file-list="form.files"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          multiple
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import type { FormInstance, UploadUserFile } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import apiClient from '@/api';

const props = defineProps<{
  visible: boolean;
  taskId: number | null;
}>();

const emit = defineEmits(['update:visible', 'submitted']);

const formRef = ref<FormInstance>();
const loading = ref(false);
const form = reactive({
  comments: '',
  files: [] as UploadUserFile[],
});

watch(() => props.visible, (newValue) => {
  if (newValue) {
    formRef.value?.resetFields();
  }
});

const handleSubmit = async () => {
  if (!props.taskId) {
    ElMessage.error('任务ID无效');
    return;
  }
  loading.value = true;
  try {
    const formData = new FormData();
    formData.append('comments', form.comments);
    form.files.forEach(file => {
      if (file.raw) {
        formData.append('files', file.raw);
      }
    });

    await apiClient.post(`/worker/${props.taskId}/submit`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    ElMessage.success('进度提交成功');
    emit('submitted');
    emit('update:visible', false);
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    loading.value = false;
  }
};
</script> 