<script setup lang="ts">
import { XMessage } from '@/hooks'
import { userStore } from '@/stores'
import sass from '@/utils/sass'
import ImageCropper from '@/components/ImageCropper/index.vue'

const props = defineProps<{
  submitAnswerPic?: string
  reportFlag: 0 | 1
  uploadLoading?: boolean
  uploadFile: any
  beforeUpload: any
}>()

const emit = defineEmits(['showPic', 'submit'])

const OSS_URL = import.meta.env.VITE_OSS_URL
const { token } = userStore()

const picList = computed(() => {
  const raw = props.submitAnswerPic || ''
  return raw
    .split(',')
    .map(i =>
      String(i || '')
        .replace(/[`]/g, '')
        .replace(/http:\/\//gi, 'https://')
        .trim(),
    )
    .filter(Boolean)
})

const maxCount = 3 // 最多上传3张图片
const canAddMore = computed(() => picList.value.length < maxCount)

const activeIndex = ref(0)
const activeUrl = computed(() => picList.value[activeIndex.value] || '')

// 记录上一次的图片数量，用于检测是否新增了图片
let prevPicLen = 0
watch(
  () => picList.value.length,
  len => {
    if (!len) {
      activeIndex.value = 0
      prevPicLen = 0
      return
    }
    // 新增图片：自动切换到最新一张（解决"上传第二张却显示第一张"的问题）
    if (len > prevPicLen) {
      activeIndex.value = len - 1
    } else if (activeIndex.value > len - 1) {
      activeIndex.value = len - 1
    }
    prevPicLen = len
  },
  { immediate: true },
)

const showCropper = ref(false)
const cropperImg = ref<Blob | File | string>('')
const uploadQueue = ref<any[]>([])
// 是否正在上传中（用于序列化裁剪/上传流程，避免并发）
const isUploading = ref(false)

function onUpload(options: any) {
  if (!canAddMore.value) {
    XMessage.error(`最多上传${maxCount}张图片`)
    return undefined
  }
  uploadQueue.value.push(options)
  processQueue()
}

function processQueue() {
  if (showCropper.value) return
  if (isUploading.value) return
  if (uploadQueue.value.length === 0) return
  const options = uploadQueue.value.shift()
  cropperImg.value = options.file
  showCropper.value = true
}

async function handleCropConfirm(blob: Blob) {
  if (typeof props.uploadFile !== 'function') {
    processQueue()
    return
  }
  isUploading.value = true
  try {
    await props.uploadFile({
      file: blob,
      isAndroid: 0,
      fromCamera: true,
    })
  } catch (e) {
    console.error('uploadFile error', e)
  } finally {
    isUploading.value = false
    // 上一张上传完成后再处理队列，避免并发上传与状态错乱
    processQueue()
  }
}

function handleCropCancel() {
  // 取消当前裁剪后继续处理队列
  processQueue()
}

function handleSelect(idx: number) {
  if (idx < 0 || idx >= picList.value.length) return
  activeIndex.value = idx
}

function handleShow(url: string) {
  if (!url) return
  emit('showPic', url)
}

function handleDel(url: string) {
  if (props.reportFlag) return
  if (!url) return
  const idx = picList.value.indexOf(url)
  emit('submit', { delUrl: url })
  if (idx !== -1 && idx <= activeIndex.value) {
    activeIndex.value = Math.max(0, activeIndex.value - 1)
  }
}
</script>

<template>
  <div class="camera-preview">
    <div class="pic-box" @click="handleShow(activeUrl)">
      <img v-if="activeUrl" :src="activeUrl" />
      <div v-show="uploadLoading" class="pic-mask">
        <Icon name="global_loading" loading size="96" />
      </div>
      <Icon
        v-if="!reportFlag && activeUrl"
        name="del_btn"
        width="32"
        class="del-btn pointer"
        @click.stop="handleDel(activeUrl)"
      ></Icon>
    </div>

    <div class="bottom-bar">
      <div class="thumbs hidden_scroll">
        <div
          v-for="(i, idx) in picList"
          :key="i"
          class="thumb pointer"
          :class="{ active: idx === activeIndex }"
          @click="handleSelect(idx)"
        >
          <img :src="i" />
          <Icon
            v-if="!reportFlag"
            name="del_btn"
            width="24"
            class="thumb-del pointer"
            @click.stop="handleDel(i)"
          ></Icon>
        </div>
      </div>

      <el-upload
        v-if="!reportFlag && canAddMore"
        class="start-btn"
        action="/api/main/sysFileInfo/tenUploadAll"
        :data="{ type: 1 }"
        :headers="{
          Authorization: token,
          'X-Tenant-Id': sass.platform.tenantId,
        }"
        accept="image/*"
        multiple
        :before-upload="beforeUpload"
        :show-file-list="false"
        :disabled="uploadLoading"
        :http-request="onUpload"
      >
        <mj-button :disabled="uploadLoading">相机/上传</mj-button>
      </el-upload>
    </div>
    <div v-if="!reportFlag" class="upload-tip">
      <span class="upload-tip-dot"></span>
      最多上传3张图片（已上传{{ picList.length }}/{{ maxCount }}张）
    </div>
    <ImageCropper
      v-model:visible="showCropper"
      :img="cropperImg"
      @confirm="handleCropConfirm"
      @cancel="handleCropCancel"
    />
  </div>
</template>

<style scoped lang="scss">
.camera-preview {
  .pic-box {
    height: 22.67vh;
    border-radius: 1.67vh;
    border: 0.33vh solid #bed5fe;
    background: #f7faf9;
    position: relative;
    background-color: #fff;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    .pic-mask {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 1.67vh;
      z-index: 10;
    }
    .del-btn {
      position: absolute;
      top: 8px;
      right: 8px;
      z-index: 11;
    }
  }

  .bottom-bar {
    margin-top: 2vh;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
  }

  .thumbs {
    flex: 1;
    display: flex;
    align-items: center;
    overflow-x: auto;
    overflow-y: hidden;
    max-width: calc(100% - 220px);
  }

  .thumb {
    position: relative;
    width: 120px;
    height: 72px;
    border-radius: 10px;
    border: 2px solid transparent;
    overflow: hidden;
    margin-right: 12px;
    flex-shrink: 0;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    &.active {
      border-color: #669cfe;
    }
    .thumb-del {
      position: absolute;
      top: 4px;
      right: 4px;
    }
  }

  .start-btn {
    display: flex;
    justify-content: flex-end;
  }

  .upload-tip {
    margin-top: 10px;
    padding: 6px 14px;
    background: #fff7e6;
    border: 1px solid #ffd591;
    border-radius: 8px;
    color: #fa8c16;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;

    .upload-tip-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #fa8c16;
      flex-shrink: 0;
    }
  }
}
</style>
