<template>
  <view class="page-contact">
    <scroll-view class="scroll-view" scroll-y>
      <view class="content-wrapper">
        <!-- 反馈表单卡片 -->
        <view class="form-card">
          <view class="card-title">意见反馈</view>

          <!-- 文本输入框 -->
          <view class="form-item">
            <textarea
              class="feedback-textarea"
              v-model="feedbackText"
              placeholder="请输入您的意见或建议..."
              maxlength="500"
              :show-confirm-bar="false"
            ></textarea>
            <view class="char-count">{{ feedbackText.length }}/500</view>
          </view>

          <!-- 图片上传 -->
          <view class="form-item">
            <view class="upload-label">上传图片（最多6张）</view>
            <view class="image-upload-container">
              <view class="image-item" v-for="(image, index) in imageList" :key="index">
                <image class="upload-image" :src="image" mode="aspectFill"></image>
                <view class="delete-btn" @click="deleteImage(index)">×</view>
              </view>
              <view class="upload-btn" v-if="imageList.length < 6" @click="chooseImage">
                <text class="upload-icon">+</text>
                <text class="upload-text">添加图片</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="submit-section">
          <button class="submit-btn" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '提交中...' : '提交反馈' }}
          </button>
        </view>

        <!-- 预留底部空间 -->
        <view class="bottom-safe-area"></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { submitFeedback, uploadFeedbackImage } from '../../utils/api.js'
import { getToken } from '../../utils/auth.js'

const feedbackText = ref('')
const imageList = ref([])
const submitting = ref(false)

onShow(() => {
  uni.setNavigationBarTitle({ title: '联系我们' })
})

/**
 * 选择图片
 */
const chooseImage = () => {
  const remainCount = 6 - imageList.value.length
  uni.chooseImage({
    count: remainCount,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      imageList.value = imageList.value.concat(res.tempFilePaths)
    }
  })
}

/**
 * 删除图片
 */
const deleteImage = (index) => {
  imageList.value.splice(index, 1)
}

/**
 * 上传单张图片
 */
const uploadImage = (filePath) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadFeedbackImage.url,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + getToken()
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.code === 200) {
            resolve(data.data.url)
          } else {
            reject(data.message || '上传失败')
          }
        } catch (e) {
          reject('上传失败')
        }
      },
      fail: (err) => {
        reject(err.errMsg || '上传失败')
      }
    })
  })
}

/**
 * 提交反馈
 */
const handleSubmit = async () => {
  if (!feedbackText.value.trim()) {
    uni.showToast({
      title: '请输入反馈内容',
      icon: 'none'
    })
    return
  }

  submitting.value = true

  try {
    // 上传所有图片
    const imageUrls = []
    if (imageList.value.length > 0) {
      uni.showLoading({ title: '上传图片中...' })

      for (const imagePath of imageList.value) {
        try {
          const url = await uploadImage(imagePath)
          imageUrls.push(url)
        } catch (err) {
          console.error('图片上传失败:', err)
          uni.hideLoading()
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          })
          submitting.value = false
          return
        }
      }

      uni.hideLoading()
    }

    // 提交反馈
    uni.showLoading({ title: '提交中...' })

    const res = await submitFeedback({
      content: feedbackText.value.trim(),
      images: imageUrls.join(',')
    })

    uni.hideLoading()

    if (res.code === 200) {
      uni.showToast({
        title: '提交成功，感谢您的反馈',
        icon: 'success',
        duration: 2000
      })

      // 清空表单
      feedbackText.value = ''
      imageList.value = []

      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 2000)
    } else {
      uni.showToast({
        title: res.message || '提交失败',
        icon: 'none'
      })
    }
  } catch (err) {
    uni.hideLoading()
    console.error('提交反馈失败:', err)
    uni.showToast({
      title: '提交失败，请稍后重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style>
.page-contact {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f6fb;
}

.scroll-view {
  flex: 1;
  height: 0;
}

.content-wrapper {
  padding: 32rpx;
  background: #f5f6fb;
  min-height: 100%;
}

/* 表单卡片 */
.form-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 16rpx 40rpx rgba(37, 52, 94, 0.08);
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #222222;
  margin-bottom: 32rpx;
}

.form-item {
  margin-bottom: 32rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

/* 文本输入框 */
.feedback-textarea {
  width: 100%;
  min-height: 300rpx;
  padding: 24rpx;
  background: #f5f6fb;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #222222;
  line-height: 1.6;
  box-sizing: border-box;
}

.char-count {
  text-align: right;
  font-size: 24rpx;
  color: #9ca2b5;
  margin-top: 12rpx;
}

/* 图片上传 */
.upload-label {
  font-size: 28rpx;
  color: #222222;
  margin-bottom: 16rpx;
}

.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
}

.upload-image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
  background: #f5f6fb;
}

.delete-btn {
  position: absolute;
  top: -12rpx;
  right: -12rpx;
  width: 48rpx;
  height: 48rpx;
  background: #ff4444;
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  line-height: 1;
  box-shadow: 0 4rpx 12rpx rgba(255, 68, 68, 0.3);
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  background: #f5f6fb;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #d0d4e0;
}

.upload-icon {
  font-size: 64rpx;
  color: #9ca2b5;
  line-height: 1;
  margin-bottom: 8rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #9ca2b5;
}

/* 提交按钮 */
.submit-section {
  margin-bottom: 32rpx;
}

.submit-btn {
  width: 100%;
  background: #5d55e8;
  color: #ffffff;
  border-radius: 16rpx;
  padding: 28rpx 0;
  text-align: center;
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 12rpx 24rpx rgba(93, 85, 232, 0.3);
  border: none;
  line-height: 1;
}

.submit-btn::after {
  border: none;
}

.submit-btn:active {
  opacity: 0.8;
}

.submit-btn[disabled] {
  opacity: 0.6;
}

.bottom-safe-area {
  height: 80rpx;
}
</style>
