<template>
  <div class="icon-editor">
    <div class="icon-preview">
      <a-image v-if="modelValue" :src="modelValue" alt="Icon Preview" class="preview-img" />
      <div v-else class="preview-placeholder">无图标</div>
    </div>
    <div class="icon-input">
      <a-input v-model:value="localValue" placeholder="图标URL" />
    </div>
    <div class="icon-upload">
      <a-button @click="handleUpload">上传</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import CommonContent from '@/api/CommonContent';
import { ref, watch } from 'vue';

const props = defineProps<{
  modelValue: string;
}>();
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
}>();

const localValue = ref(props.modelValue);

watch(localValue, (newValue) => {
  emit('update:modelValue', newValue);
});
watch(() => props.modelValue, (newValue) => {
  localValue.value = newValue;
});

async function handleUpload() {
  const res = await uni.chooseImage({
    count: 1,
  });
  if (res.tempFilePaths.length > 0) {
    const url = await CommonContent.uploadFile(res.tempFilePaths[0]);
    localValue.value = url.fullurl;
  }
}
</script>

<style scoped>
.icon-editor {
  display: flex;
  align-items: center;
  gap: 8px;
}

.icon-preview {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-placeholder {
  font-size: 12px;
  color: #999;
}

.icon-input {
  flex: 1;
}

.icon-upload {
  white-space: nowrap;
}
</style>