<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '发起投诉',
  },
}
</route>

<template>
  <view class="min-h-screen bg-gray-50 p-4">
    <view class="bg-white rounded-2xl shadow-sm p-4">
      <!-- 投诉分类 -->
      <view class="mb-4">
        <text class="text-sm text-gray-600 mb-2 block">投诉分类</text>
        <view class="grid grid-cols-2 gap-2">
          <view
            v-for="item in complaintClasses"
            :key="item.value"
            class="h-12 px-4 bg-gray-50 rounded-lg flex items-center justify-center"
            :class="{
              'bg-sky-50 border border-sky-200': selectedClass === item.value,
              'border border-gray-100': selectedClass !== item.value,
            }"
            @click="selectedClass = item.value"
          >
            <text
              :class="{
                'text-sky-600': selectedClass === item.value,
                'text-gray-600': selectedClass !== item.value,
              }"
            >
              {{ item.label }}
            </text>
          </view>
        </view>
      </view>

      <!-- 投诉内容 -->
      <view class="mb-4">
        <text class="text-sm text-gray-600 mb-2 block">投诉详情</text>
        <textarea
          v-model="complaintContent"
          class="w-full h-40 px-4 py-3 bg-gray-50 rounded-lg text-gray-800 placeholder-gray-400"
          placeholder="请详细描述您遇到的问题..."
          maxlength="500"
        />
        <text class="text-xs text-gray-400 text-right block mt-1">
          {{ complaintContent.length }}/500
        </text>
      </view>

      <!-- 图片上传 -->
      <view class="mb-4">
        <text class="text-sm text-gray-600 mb-2 block">上传证据（选填）</text>
        <view class="grid grid-cols-3 gap-2">
          <view v-for="(image, index) in imageList" :key="index" class="relative aspect-square">
            <image :src="image" class="w-full h-full rounded-lg object-cover" mode="aspectFill" />
            <view
              class="absolute top-1 right-1 w-6 h-6 bg-black/50 rounded-full flex items-center justify-center"
              @click="removeImage(index)"
            >
              <i class="i-carbon-close text-white text-sm"></i>
            </view>
          </view>
          <view
            v-if="imageList.length < 9"
            class="aspect-square bg-gray-50 rounded-lg flex items-center justify-center border border-dashed border-gray-200"
            @click="chooseImage"
          >
            <i class="i-carbon-image text-gray-400 text-2xl"></i>
          </view>
        </view>
        <text class="text-xs text-gray-400 mt-1 block">最多上传9张图片，每张不超过5MB</text>
      </view>

      <!-- 提交按钮 -->
      <button
        class="w-full h-12 bg-gradient-to-r from-sky-400 to-indigo-400 text-white rounded-lg text-base flex items-center justify-center shadow-sm hover:shadow-md transition-shadow"
        :disabled="!isValid"
        :class="{ 'opacity-50': !isValid }"
        @click="submitComplaint"
      >
        提交投诉
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { addComplaintAPI } from '@/service/feedback'
import { uploadImageAPI } from '@/service/file'
import { onLoad } from '@dcloudio/uni-app'

const id = ref('')
onLoad((options) => {
  id.value = options.id
})

// 投诉分类选项
const complaintClasses = [
  { label: '虚假宣传', value: '虚假宣传' },
  { label: '微商', value: '微商' },
  { label: '诈骗', value: '诈骗' },
  { label: '个人信息不符', value: '个人信息不符' },
]

const selectedClass = ref('')
const complaintContent = ref('')
const imageList = ref<string[]>([])

// 验证表单是否有效
const isValid = computed(() => {
  return selectedClass.value && complaintContent.value.trim().length > 0
})

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 9 - imageList.value.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
    })

    // 检查图片大小
    const tempFiles = res.tempFiles as UniApp.ChooseImageSuccessCallbackResultFile[]
    const tempFilePaths = res.tempFilePaths as string[]

    const validImages = tempFilePaths.filter((path) => {
      const file = tempFiles.find((f) => f.path === path)
      return file && file.size <= 5 * 1024 * 1024 // 5MB
    })

    if (validImages.length !== tempFilePaths.length) {
      uni.showToast({
        title: '部分图片超过5MB限制',
        icon: 'none',
      })
    }

    imageList.value.push(...validImages)
  } catch (error) {
    console.error('选择图片失败:', error)
  }
}

// 移除图片
const removeImage = (index: number) => {
  imageList.value.splice(index, 1)
}

// 上传图片
const uploadImages = async () => {
  const uploadedUrls: string[] = []

  for (const image of imageList.value) {
    try {
      const res = await uploadImageAPI(image, 'complaint')
      if (res.url) {
        uploadedUrls.push(res.url)
      }
    } catch (error) {
      console.error('上传图片失败:', error)
      uni.showToast({
        title: '图片上传失败',
        icon: 'none',
      })
    }
  }

  return uploadedUrls
}

// 提交投诉
const submitComplaint = async () => {
  if (!isValid.value) return

  try {
    uni.showLoading({ title: '提交中...' })

    // 上传图片
    const imageUrls = await uploadImages()

    // 提交投诉
    await addComplaintAPI({
      userId: id.value, // TODO: 从路由参数或全局状态获取被投诉人ID
      complaintClass: selectedClass.value as any,
      complaintContent: complaintContent.value.trim(),
      complaintImageList: imageUrls,
    })

    uni.hideLoading()
    uni.showToast({
      title: '提交成功',
      icon: 'success',
    })

    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none',
    })
  }
}
</script>
