<template>
  <a-modal
      :visible="previewModalVisible"
      title="图像详情"
      width="80%"
      :footer="footerButtons"
      :mask-closable="true"
      @update:visible="emit('update:previewModalVisible', $event)"
      :confirm-loading="loading"
  >
    <div v-if="previewImage" class="modal-image-viewer">
      <img :src="getImageUrl(previewImage.imagePath)" :alt="editingData.imageName" class="preview-image" />

      <div class="image-details">
        <a-form layout="vertical" :model="editingData">
          <a-form-item label="图片名称" field="imageName">
            <a-input v-model="editingData.imageName" />
          </a-form-item>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="大小" field="size">
                <a-input :model-value="formatFileSize(editingData.size || 0)" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="尺寸" field="imageResolution">
                <a-input v-model="editingData.imageResolution" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="采集员ID" field="collectId">
                <a-input v-model="editingData.collectId" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="采集员姓名" field="collectorName">
                <a-input v-model="editingData.collectorName" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="来源" field="imageSource">
                <a-input v-model="editingData.imageSource" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="图片类型" field="imageType">
                <a-select v-model="editingData.imageType">
                  <a-option value="DEFECT">缺陷影像</a-option>
                  <a-option value="TYPICAL">典型影像</a-option>
                  <a-option value="OTHER">其他影像</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="图片类型描述" field="imageTypeLabel">
            <a-textarea
                v-model="editingData.imageTypeLabel"
                :auto-size="{ minRows: 2, maxRows: 4 }"
            />
          </a-form-item>
        </a-form>
      </div>
    </div>
    <template #footer>
      <a-button @click="emit('update:previewModalVisible', false)">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleSave">保存</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import axios from 'axios'

const props = defineProps<{
  previewModalVisible: boolean
  previewImage: {
    imagePath: string
    imageName: string
    size?: number
    imageResolution?: string
    collectId?: string
    collectorName?: string
    imageSource?: string
    imageType?: string
    imageTypeLabel?: string
    partId?: string
  } | null
  selectedImage: any | null
}>()

const emit = defineEmits<{
  'update:previewModalVisible': [visible: boolean]
  'save': [data: any]
}>()

const loading = ref(false)
const editingData = ref<{
  imagePath: string
  imageName: string
  size?: number
  imageResolution?: string
  collectId?: string
  collectorName?: string
  imageSource?: string
  imageType?: string
  imageTypeLabel?: string
  partId?: string
  imageId?:string
}>({
  imagePath: '',
  imageName: '',
  size: 0,
  imageResolution: '',
  collectId: '',
  collectorName: '',
  imageSource: '',
  imageType: '',
  imageTypeLabel: '',
  partId: '',
  imageId:''
})

// 监听预览图片变化，初始化编辑数据
watch(() => props.previewImage, (newVal) => {
  if (newVal) {
    editingData.value = { ...newVal }
  }
}, { immediate: true, deep: true })

const getImageUrl = (imagePath: string): string => {
  if (!imagePath) return ''
  if (imagePath.startsWith('http')) return imagePath
  const baseUrl = 'http://pms.dtyx.net:9158'
  return `${baseUrl}${imagePath}`
}

const formatFileSize = (size: number): string => {
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`
  return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`
}

const handleSave = async () => {
  if (!editingData.value.imageName?.trim()) {
    Message.error('图片名称不能为空')
    return
  }

  if (!editingData.value.partId) {
    Message.error('缺少部件ID，无法保存')
    return
  }

  try {
    loading.value = true

    // 构造请求数据
    const requestData = {
      collectId: editingData.value.collectId,
      collectorName: editingData.value.collectorName,
      imageSource: editingData.value.imageSource,
      imageType: editingData.value.imageType,
      imageTypeLabel: editingData.value.imageTypeLabel,
      imageList: [
        {
          imageId: editingData.value.imageId,
          imageName: editingData.value.imageName,
          imageResolution: editingData.value.imageResolution,
        }
      ],
    }
    console.log("requestData:",requestData);

    // 调用接口更新数据
    const response = await axios.post(
        `http://pms.dtyx.net:9158/image/setting-info/${editingData.value.partId}`,
        requestData
    )
    if (response.data && response.data.code === 200 && response.data.success) {
      Message.success('图片信息保存成功')
      emit('save', editingData.value)
      emit('update:previewModalVisible', false)
    } else {
      Message.error(response.data?.message || '保存失败')
    }
  } catch (error) {
    console.error('保存图片信息失败:', error)
    Message.error('保存失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.modal-image-viewer {
  display: flex;
  gap: 24px;
  align-items: flex-start;

  .preview-image {
    flex: 1;
    max-width: 60%;
    max-height: 500px;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  }

  .image-details {
    flex: 1;
    padding: 16px;

    :deep(.arco-form) {
      .arco-form-item {
        margin-bottom: 16px;
      }
    }
  }
}

@media (max-width: 768px) {
  .modal-image-viewer {
    flex-direction: column;

    .preview-image {
      max-width: 100%;
    }
  }
}
</style>
