<template>
  <div v-if="open" class="modal-mask" @click.self="$emit('close')">
    <section class="modal-card">
      <div class="modal-header">
        <div>
          <h3>{{ form.id ? '编辑商品' : '添加新商品' }}</h3>
          <p class="tag">封面图和最多 5 张商品截图共用这一套编辑表单。</p>
        </div>
        <button class="ghost" @click="$emit('close')">关闭</button>
      </div>

      <div class="modal-body">
        <div class="form-field">
          <label>商品名称</label>
          <input v-model="form.name" placeholder="商品名称" />
        </div>
        <div class="form-row">
          <div class="form-field">
            <label>原价（元）</label>
            <input v-model.number="form.price" type="number" step="0.01" />
          </div>
          <div class="form-field">
            <label>折扣价（元，可选）</label>
            <input v-model.number="form.discountPrice" type="number" step="0.01" />
            <p class="tag">留空或不小于原价时，将不启用折扣。</p>
          </div>
        </div>
        <div class="form-field">
          <label>封面链接（http）</label>
          <input v-model="form.coverUrl" placeholder="http://..." />
        </div>
        <div class="form-field">
          <div class="field-head">
            <label>商品库存</label>
            <span class="tag">共 {{ form.inventoryItems.length }} 条</span>
            <button class="ghost small" type="button" @click="addInventoryItem">添加商品库存</button>
          </div>
          <p class="tag">每个输入框保存一条可发放内容，购买后会直接展示给用户。</p>
          <div class="inventory-list">
            <div v-for="(_, index) in form.inventoryItems" :key="index" class="inventory-row">
              <input
                :ref="(el) => setInventoryInputRef(el, index)"
                v-model="form.inventoryItems[index]"
                placeholder="库存内容，可填卡密、下载链接等"
              />
              <button
                v-if="form.inventoryItems.length > 1"
                class="ghost small"
                type="button"
                @click="removeInventoryItem(index)"
              >
                删除
              </button>
            </div>
          </div>
        </div>
        <div class="form-field">
          <label>商品截图链接（最多 5 个）</label>
          <div class="screenshot-grid">
            <input
              v-for="(_, index) in screenshotInputSlots"
              :key="index"
              v-model="form.screenshotUrls[index]"
              :placeholder="`截图链接 ${index + 1}（http://...）`"
            />
          </div>
        </div>
        <div class="form-field">
          <label>商品介绍（Markdown）</label>
          <textarea v-model="form.description"></textarea>
        </div>
        <div class="form-field">
          <label>商品标签（英文逗号分隔）</label>
          <input v-model="form.tagsText" placeholder="例如: chatgpt, linux, 域名" />
          <p class="tag">用于前端搜索与筛选，多个标签用英文逗号分开</p>
        </div>
        <div class="form-field">
          <label>是否上架</label>
          <select v-model="form.active">
            <option :value="true">上架</option>
            <option :value="false">下架</option>
          </select>
        </div>
        <div class="form-row">
          <div class="form-field">
            <label>
              <input type="checkbox" v-model="form.requireLogin" class="inline-checkbox" />
              需要登录才能购买
            </label>
            <p class="tag">开启后未登录用户将无法完成购买</p>
          </div>
          <div class="form-field">
            <label>每账户最多购买数量（0 = 不限）</label>
            <input v-model.number="form.maxPerAccount" type="number" min="0" step="1" placeholder="0 表示不限制" />
          </div>
        </div>
        <div class="form-row">
          <div class="form-field">
            <label>发货模式</label>
            <select v-model="form.deliveryMode">
              <option value="auto">自动发货（下单后自动提取内容）</option>
              <option value="manual">手动发货（管理员手动处理）</option>
            </select>
            <p class="tag">手动发货不会自动提取库存内容</p>
          </div>
        </div>
        <div class="form-row">
          <div class="form-field">
            <label>
              <input type="checkbox" v-model="form.showNote" class="inline-checkbox" />
              下单时显示备注输入框
            </label>
          </div>
          <div class="form-field">
            <label>
              <input type="checkbox" v-model="form.showContact" class="inline-checkbox" />
              下单时显示联系方式输入框
            </label>
            <p class="tag">包含手机号和邮箱两个输入框</p>
          </div>
        </div>
      </div>

      <div class="modal-actions">
        <button class="primary" @click="handleSubmit">{{ form.id ? '更新商品' : '新增商品' }}</button>
        <button class="ghost" @click="resetForm">重置表单</button>
      </div>
    </section>
  </div>
</template>

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

const MAX_SCREENSHOT_URLS = 5
const MAX_INVENTORY_ITEMS = 500
const screenshotInputSlots = Array.from({ length: MAX_SCREENSHOT_URLS })
const inventoryInputRefs = ref([])

const props = defineProps({
  open: { type: Boolean, default: false },
  editItem: { type: Object, default: null }
})

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

const createScreenshotSlots = (values = []) =>
  Array.from({ length: MAX_SCREENSHOT_URLS }, (_, i) => values[i] || '')

const createInventoryItems = (values = []) => {
  const items = values
    .map((v) => (v || '').trim())
    .filter((v) => v)
    .slice(0, MAX_INVENTORY_ITEMS)
  return items.length ? items : ['']
}

const normalizeInventoryItems = (values = []) =>
  values
    .map((item) => (item || '').trim())
    .filter((item) => item)
    .slice(0, MAX_INVENTORY_ITEMS)

const normalizeScreenshotUrls = (values = []) =>
  values.map((item) => item.trim()).filter(Boolean).slice(0, MAX_SCREENSHOT_URLS)

const makeEmptyForm = () => ({
  id: '',
  name: '',
  price: 0,
  discountPrice: 0,
  tagsText: '',
  coverUrl: '',
  screenshotUrls: createScreenshotSlots(),
  inventoryItems: createInventoryItems(),
  description: '',
  active: true,
  requireLogin: false,
  maxPerAccount: 0,
  deliveryMode: 'auto',
  showNote: false,
  showContact: false
})

const form = reactive(makeEmptyForm())

const fillForm = (item) => {
  Object.assign(form, {
    id: item?.id || '',
    name: item?.name || '',
    price: item?.price || 0,
    discountPrice: item?.discountPrice || 0,
    tagsText: (item?.tags || []).join(','),
    coverUrl: item?.coverUrl || '',
    screenshotUrls: createScreenshotSlots(item?.screenshotUrls || []),
    inventoryItems: createInventoryItems(item?.codes || []),
    description: item?.description || '',
    active: item?.active ?? true,
    requireLogin: item?.requireLogin ?? false,
    maxPerAccount: item?.maxPerAccount ?? 0,
    deliveryMode: item?.deliveryMode || 'auto',
    showNote: item?.showNote ?? false,
    showContact: item?.showContact ?? false
  })
}

const resetForm = () => {
  Object.assign(form, makeEmptyForm())
}

watch(
  () => props.editItem,
  (item) => {
    if (item) {
      fillForm(item)
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

const setInventoryInputRef = (el, index) => {
  if (!el) return
  inventoryInputRefs.value[index] = el
}

const addInventoryItem = async () => {
  form.inventoryItems.push('')
  await nextTick()
  const lastIndex = form.inventoryItems.length - 1
  const input = inventoryInputRefs.value[lastIndex]
  if (input?.focus) input.focus()
  if (input?.scrollIntoView) input.scrollIntoView({ block: 'center', behavior: 'smooth' })
}

const removeInventoryItem = async (index) => {
  if (form.inventoryItems.length <= 1) {
    form.inventoryItems[0] = ''
    return
  }
  form.inventoryItems.splice(index, 1)
  inventoryInputRefs.value.splice(index, 1)
  await nextTick()
  const targetIndex = Math.min(index, form.inventoryItems.length - 1)
  const input = inventoryInputRefs.value[targetIndex]
  if (input?.focus) input.focus()
}

const handleSubmit = () => {
  emit('submit', {
    id: form.id,
    name: form.name,
    price: form.price,
    discountPrice: form.discountPrice || 0,
    tags: form.tagsText,
    coverUrl: form.coverUrl,
    codes: normalizeInventoryItems(form.inventoryItems),
    screenshotUrls: normalizeScreenshotUrls(form.screenshotUrls),
    description: form.description,
    active: form.active,
    requireLogin: form.requireLogin,
    maxPerAccount: form.maxPerAccount || 0,
    deliveryMode: form.deliveryMode || 'auto',
    showNote: form.showNote,
    showContact: form.showContact
  })
}
</script>

<style scoped>
.modal-mask {
  position: fixed;
  inset: 0;
  z-index: 40;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background: rgba(30, 28, 32, 0.35);
  backdrop-filter: blur(8px);
}

.modal-card {
  width: min(920px, 100%);
  max-height: calc(100vh - 48px);
  overflow: auto;
  padding: 28px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid var(--line);
  box-shadow: 0 24px 60px rgba(33, 33, 40, 0.2);
}

.modal-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 22px;
}

.modal-body {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.modal-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid var(--line);
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 12px;
}

.form-field input,
.form-field textarea {
  border-radius: 8px;
  border: 1px solid var(--line);
  background: rgba(255, 255, 255, 0.7);
  padding: 10px 12px;
  font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
}

.form-field textarea {
  min-height: 120px;
  resize: vertical;
}

select {
  border-radius: 8px;
  border: 1px solid var(--line);
  background: rgba(255, 255, 255, 0.7);
  padding: 10px 12px;
  font-family: 'KaiTi', 'STKaiti', '楷体', '楷体_GB2312', serif;
  font-size: 15px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.field-head {
  display: flex;
  align-items: center;
  gap: 12px;
}

.inventory-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.inventory-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.inventory-row input {
  flex: 1;
}

.screenshot-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

.small {
  padding: 7px 13px;
  font-size: 13px;
  border-radius: 999px;
}

.tag {
  font-size: 14px;
  color: var(--muted);
}

.inline-checkbox {
  width: auto;
  margin-right: 6px;
  accent-color: var(--accent);
  cursor: pointer;
}

.form-field label {
  display: flex;
  align-items: center;
  font-weight: 600;
  color: var(--text);
  cursor: default;
}

@media (max-width: 900px) {
  .modal-mask {
    padding: 12px;
  }

  .modal-card {
    padding: 18px;
    max-height: calc(100vh - 24px);
  }

  .form-row,
  .screenshot-grid {
    grid-template-columns: 1fr;
  }

  .field-head {
    flex-wrap: wrap;
  }

  .inventory-row {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
