<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { dealUploadTask } from '@/api/schedule/task'
import useUpload from '@/hooks/useUpload'

const toast = useToast()

const taskId = ref('')
const checkId = ref('')

// 表单数据
const formData = ref({
  attachments: '',
  remark: '',
})

// 上传文件列表
const uploadFiles = ref<any[]>([])

// 初始化useUpload
const { run: uploadRun, loading: uploadLoading } = useUpload({
  fileType: 'file',
  success: (data) => {
    console.log('上传成功:', data)

    // 构建文件对象
    const fileObj = {
      url: data.url || '',
      originalFilename: data.originalFilename || data.name || '',
      name: data.fileName || data.name || '',
    }

    // 添加到上传文件列表
    uploadFiles.value.push(fileObj)

    // 更新附件字段
    const fileNames = uploadFiles.value.map((f) => {
      try {
        const response = JSON.parse(f.response)
        return response.data.fileName
      }
      catch (error) {
        console.error('解析文件响应失败:', error)
        return ''
      }
    }).filter(Boolean)

    formData.value.attachments = fileNames.join(',')
    console.log('文件名称:', formData.value.attachments)
  },
  error: (err) => {
    console.error('上传失败:', err)
    toast.error('上传失败，请重试')
  },
})

// 处理删除文件
function handleRemoveFile(file: any) {
  const index = uploadFiles.value.findIndex(f => f.url === file.url)
  if (index !== -1) {
    uploadFiles.value.splice(index, 1)

    // 更新附件字段
    const fileNames = uploadFiles.value.map((f) => {
      try {
        const response = JSON.parse(f.response)
        return response.data.fileName
      }
      catch (error) {
        console.error('解析文件响应失败:', error)
        return ''
      }
    }).filter(Boolean)

    formData.value.attachments = fileNames.join(',')
  }
}

// 提交表单
async function submitForm() {
  // 这里可以添加表单验证逻辑

  // 检查是否有文件上传
  if (uploadFiles.value.length === 0) {
    toast.info('请上传附件')
    return
  }

  // 构建请求参数
  const params = {
    taskId: Number(taskId.value),
    checkId: Number(checkId.value),
    ...formData.value,
    id: taskId.value,
    attachment: uploadFiles.value.map(f => f.name).join(','),
    attachmentName: uploadFiles.value.map(f => f.originalFilename).join(','),
    remark: formData.value.remark,
  }

  // 调用处理任务附件接口
  try {
    const res: any = await dealUploadTask(params)
    if (res.code === 200) {
      toast.success('提交成功')
      // 跳转回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
    else {
      toast.error(res.msg || '提交失败，请重试')
      return
    }
  }
  catch (error) {
    toast.error('提交失败，请重试')
    return
  }
}

// 页面加载时获取参数
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  // 使用类型断言获取options
  const options = (currentPage as any).options || {}
  taskId.value = options.id || ''
  checkId.value = options.checkId || ''
})
</script>

<template>
  <view class="page min-h-screen bg-gray-100 p-4">
    <view class="rounded-lg bg-white p-4 shadow-sm">
      <!-- 上传附件 -->
      <view class="mb-6">
        <view class="flex items-center justify-between">
          <text class="font-medium">上传附件</text>
          <wd-button type="text" @click="uploadRun">
            点击上传附件
          </wd-button>
        </view>
        <view v-for="(file, index) in uploadFiles" :key="index" class="mt-2 flex items-center justify-between">
          <wd-icon name="close-circle" class="mr-2 text-red-500" @click="handleRemoveFile(file)" />
          <wd-text :text="file.originalFilename" class="flex-1" />
        </view>
      </view>

      <!-- 备注 -->
      <view class="mb-6">
        <text class="mb-2 block font-medium">备注</text>
        <wd-textarea v-model="formData.remark" placeholder="请填写备注" auto-height :maxlength="120" clearable show-word-limit />
      </view>

      <!-- 提交按钮 -->
      <view class="mt-8 flex justify-center">
        <wd-button
          type="primary"
          size="large"
          @click="submitForm"
        >
          提交
        </wd-button>
      </view>
      <wd-toast />
    </view>
  </view>
</template>
