<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  ratios: {
    type: Array,
    default: () => [
      { value: '1:1', name: '头像' },
      { value: '3:2', name: '文章配图' },
      { value: '3:4', name: '社交媒体' },
      { value: '4:3', name: '公众号配图' },
      { value: '9:16', name: '海报图' },
    ],
  },
})

const emit = defineEmits(['update:modelValue'])

const selectedRatio = ref('')
const customRatio = ref({ width: 1, height: 2 })

const selectRatio = (ratio) => {
  selectedRatio.value = ratio
  emit('update:modelValue', ratio)
}

watch(customRatio, (newValue) => {
  const ratio = `${newValue.width}:${newValue.height}`
  selectRatio(ratio)
}, { deep: true })

const onlyAllowNumber = value => !value || /^\d+$/.test(value)
</script>

<template>
  <div class=" p-1 rounded-lg">
    <div class="grid grid-cols-5 gap-1 mb-2">
      <button
        v-for="(ratio, index) in ratios" :key="index"
        class=" rounded  border-gray-400 text-sm min-w-10 flex flex-col justify-center items-center"
        :class="{ 'text-blue-400': selectedRatio === ratio.value }"
        style="font-size: 10px; border-width: 1px ;"
        @click="selectRatio(ratio.value)"
      >
        <span>{{ ratio.value }}</span>
        <span>{{ ratio.name }}</span>
      </button>
    </div>
    <div class="grid grid-cols-2 gap-1 ">
      <button
        class=" rounded  border-gray-500  text-sm min-w-10 flex flex-col justify-center items-center"
        :class="{ 'text-blue-400': selectedRatio === '16:9' }"
        style="font-size: 10px; border-width: 1px ;"
        @click="selectRatio('16:9')"
      >
        <span>16:9</span>
        <span>电脑壁纸</span>
      </button>
      <div class="flex flex-col justify-center items-center border-gray-500  rounded px-2" style="border-width: 1px; font-size: 10px;">
        <span class="mr-2" :class="{ 'text-blue-400': ratios.map(item => item.value).includes(selectedRatio) === -1 && selectedRatio !== '16:9' }">自定义</span>
        <div class="grid grid-cols-9 items-center">
          <n-input v-model:value="customRatio.width" type="text" :allow-input="onlyAllowNumber" class=" col-span-4" size="tiny" />
          <span class="mx-1">:</span>
          <n-input v-model:value="customRatio.height" type="text" :allow-input="onlyAllowNumber" class=" col-span-4" size="tiny" />
        </div>
      </div>
    </div>
  </div>
</template>
