<template>
  <div class="check-upload-page">
    <div class="header">
      <h2>产品图片上传</h2>
    </div>

    <div class="form">
      <div class="form-item">
        <label>产品编号</label>
        <el-input
          v-model="productCode"
          placeholder="请扫描或输入产品编号"
          clearable
          @keyup.enter="focusRemark"
        />
      </div>

      <div class="form-item">
        <label>备注</label>
        <el-input
          ref="remarkInput"
          v-model="remark"
          placeholder="请输入备注"
          clearable
        />
      </div>

      <div class="form-item">
        <label>拍照</label>
        <div class="photo-area">
          <input
            ref="fileInput"
            class="file-input"
            type="file"
            accept="image/*"
            capture="environment"
            @change="onFileChange"
          />
          <el-button
            type="primary"
            class="btn-photo"
            @click="triggerCamera"
          >
            拍照
          </el-button>
        </div>
        <div v-if="imagePreview" class="preview">
          <img :src="imagePreview" alt="预览" />
        </div>
      </div>

      <div class="form-item">
        <el-button
          type="success"
          class="btn-submit"
          :loading="uploading"
          @click="handleUpload"
        >
          上传
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { ElMessage } from 'element-plus'

const ExecHttpRequest = inject('ExecHttpRequest')

const productCode = ref('')
const remark = ref('')
const imagePreview = ref('')
const uploading = ref(false)

const fileInput = ref(null)
const remarkInput = ref(null)

const focusRemark = () => {
  if (remarkInput.value && typeof remarkInput.value.focus === 'function') {
    remarkInput.value.focus()
  }
}

const triggerCamera = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

const onFileChange = (e) => {
  const files = e && e.target ? e.target.files : null
  if (!files || !files[0]) {
    imagePreview.value = ''
    return
  }
  const file = files[0]
  if (!/^image\//.test(file.type)) {
    ElMessage.error('请选择图片文件')
    imagePreview.value = ''
    return
  }
  const reader = new FileReader()
  reader.onload = (ev) => {
    imagePreview.value = ev.target && ev.target.result ? ev.target.result.toString() : ''
  }
  reader.readAsDataURL(file)
}

const handleUpload = async () => {
  if (!productCode.value.trim()) {
    ElMessage.error('请先扫描或输入产品编号')
    return
  }
  if (!remark.value.trim()) {
    ElMessage.error('请先输入备注')
    return
  }
  if (!imagePreview.value) {
    ElMessage.error('请先拍照')
    return
  }
  if (!ExecHttpRequest) {
    ElMessage.error('上传服务未初始化')
    return
  }

  uploading.value = true
  try {
    const payload = {
      ProductCode: productCode.value.trim(),
      Remark: remark.value.trim(),
      ImageBase64: imagePreview.value
    }

    const baseUrl = window.g && window.g.API_MES_Controller_URL ? window.g.API_MES_Controller_URL : ''
    const url = baseUrl + '/api/checkimage/upload'

    const res = await ExecHttpRequest(url, 'post', payload)
    const data = res && res.data ? res.data : null

    if (!data || data.success !== true) {
      ElMessage.error((data && data.message) || '上传失败')
      return
    }

    ElMessage.success('上传成功')

    // 保留产品编号，方便连续拍摄，清空备注和图片
    remark.value = ''
    imagePreview.value = ''
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  } catch (err) {
    console.error('上传异常:', err)
    ElMessage.error('上传异常，请稍后重试')
  } finally {
    uploading.value = false
  }
}
</script>

<style lang="scss" scoped>
.check-upload-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  box-sizing: border-box;
}

.header {
  width: 100%;
  max-width: 480px;
  text-align: center;
  margin-bottom: 8px;

  h2 {
    font-size: 18px;
    margin: 0;
  }
}

.form {
  width: 100%;
  max-width: 480px;
}

.form-item {
  margin-bottom: 12px;

  label {
    display: block;
    font-size: 14px;
    margin-bottom: 4px;
  }
}

.photo-area {
  display: flex;
  align-items: center;
}

.file-input {
  display: none;
}

.btn-photo,
.btn-submit {
  width: 100%;
}

.preview {
  margin-top: 8px;
  text-align: center;

  img {
    max-width: 100%;
    max-height: 240px;
    border-radius: 4px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);
  }
}
</style>
