<!-- 规格值管理面板（展开行内嵌） -->
<template>
  <div class="spec-value-panel">
    <div class="spec-value-header">
      <span class="label">「{{ spec.specName }}」的规格值</span>
      <span class="tip">点击标签编辑，拖拽排序</span>
    </div>

    <div class="spec-value-body">
      <!-- 已有规格值 tags -->
      <a-spin :spinning="loading">
        <div class="tags-wrap">
          <template v-for="item in values" :key="item.specValueId">
            <a-tag
              :closable="true"
              class="spec-tag"
              @click="openEditValue(item)"
              @close.prevent="removeValue(item)"
            >
              <span v-if="item.image" class="tag-img-wrap">
                <img :src="item.image" class="tag-img" alt="" />
              </span>
              {{ item.specValue }}
              <span v-if="item.sortNumber !== undefined" class="tag-sort">{{ item.sortNumber }}</span>
            </a-tag>
          </template>

          <!-- 添加输入框 -->
          <template v-if="addingInput">
            <a-input
              ref="inputRef"
              v-model:value="newValueText"
              size="small"
              class="tag-input"
              placeholder="输入规格值后回车"
              @blur="confirmAdd"
              @keyup.enter="confirmAdd"
              @keyup.esc="cancelAdd"
            />
          </template>
          <template v-else>
            <a-tag
              class="add-tag"
              @click="startAdd"
            >
              <PlusOutlined />
              添加规格值
            </a-tag>
          </template>
        </div>
      </a-spin>
    </div>

    <!-- 规格值编辑弹窗（点击已有 tag 时） -->
    <a-modal
      v-model:open="showValueEdit"
      title="编辑规格值"
      :width="420"
      :maskClosable="false"
      @ok="saveValueEdit"
      @cancel="showValueEdit = false"
    >
      <a-form
        ref="valueFormRef"
        :model="editingValue"
        :rules="valueRules"
        :label-col="{ flex: '80px' }"
        :wrapper-col="{ flex: '1' }"
        style="margin-top: 16px"
      >
        <a-form-item label="规格值" name="specValue">
          <a-input
            v-model:value="editingValue.specValue"
            placeholder="如：红色、XL、棉"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="图片" name="image">
          <div class="value-image-row">
            <a-image
              v-if="editingValue.image"
              :src="editingValue.image"
              :width="56"
              :height="56"
              style="object-fit: cover; border-radius: 4px; margin-right: 8px"
            />
            <a-upload
              :show-upload-list="false"
              accept="image/*"
              :before-upload="(file: File) => handleImageUpload(file)"
            >
              <a-button size="small">
                <template #icon><UploadOutlined /></template>
                {{ editingValue.image ? '更换图片' : '上传图片' }}
              </a-button>
            </a-upload>
            <a-button
              v-if="editingValue.image"
              size="small"
              danger
              style="margin-left: 6px"
              @click="editingValue.image = ''"
            >删除</a-button>
          </div>
          <div class="ele-text-secondary" style="font-size: 12px; margin-top: 4px">
            适用于颜色类规格，上传颜色色板图片
          </div>
        </a-form-item>
        <a-form-item label="排序号" name="sortNumber">
          <a-input-number
            v-model:value="editingValue.sortNumber"
            :min="0"
            :max="9999"
            class="ele-fluid"
            placeholder="数值越小越靠前"
          />
        </a-form-item>
        <a-form-item label="备注" name="comments">
          <a-input v-model:value="editingValue.comments" placeholder="可选" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, nextTick } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { PlusOutlined, UploadOutlined } from '@ant-design/icons-vue';
  import type { ShopSpec } from '@/api/shop/shopSpec/model';
  import type { ShopSpecValue } from '@/api/shop/shopSpecValue/model';
  import {
    listShopSpecValue,
    addShopSpecValue,
    updateShopSpecValue,
    removeShopSpecValue
  } from '@/api/shop/shopSpecValue';
  import { uploadFile } from '@/api/system/file';

  const props = defineProps<{
    spec: ShopSpec;
  }>();

  const loading = ref(false);
  const values = ref<ShopSpecValue[]>([]);

  // 快捷添加
  const addingInput = ref(false);
  const newValueText = ref('');
  const inputRef = ref<any>(null);

  // 编辑弹窗
  const showValueEdit = ref(false);
  const valueFormRef = ref<any>(null);
  const editingValue = reactive<ShopSpecValue>({
    specValueId: undefined,
    specId: undefined,
    specValue: '',
    image: '',
    comments: '',
    sortNumber: 100
  });

  const valueRules: Record<string, any> = {
    specValue: [{ required: true, message: '请填写规格值', trigger: 'blur' }]
  };

  // 加载规格值列表
  const loadValues = async () => {
    if (!props.spec.specId) return;
    loading.value = true;
    try {
      const data = await listShopSpecValue({ specId: props.spec.specId } as any);
      values.value = data || [];
    } catch (e: any) {
      message.error(e.message || '加载规格值失败');
    } finally {
      loading.value = false;
    }
  };

  watch(
    () => props.spec.specId,
    (id) => {
      if (id) loadValues();
    },
    { immediate: true }
  );

  // 快捷添加 - 开始
  const startAdd = () => {
    addingInput.value = true;
    newValueText.value = '';
    nextTick(() => {
      inputRef.value?.focus();
    });
  };

  // 快捷添加 - 确认
  const confirmAdd = async () => {
    const val = newValueText.value.trim();
    if (!val) {
      cancelAdd();
      return;
    }
    try {
      await addShopSpecValue({
        specId: props.spec.specId,
        specValue: val,
        sortNumber: 100
      });
      message.success('添加成功');
      newValueText.value = '';
      addingInput.value = false;
      loadValues();
    } catch (e: any) {
      message.error(e.message || '添加失败');
    }
  };

  // 快捷添加 - 取消
  const cancelAdd = () => {
    addingInput.value = false;
    newValueText.value = '';
  };

  // 打开编辑弹窗
  const openEditValue = (item: ShopSpecValue) => {
    Object.assign(editingValue, {
      specValueId: item.specValueId,
      specId: item.specId,
      specValue: item.specValue,
      image: item.image || '',
      comments: item.comments || '',
      sortNumber: item.sortNumber ?? 100
    });
    showValueEdit.value = true;
  };

  // 保存编辑
  const saveValueEdit = async () => {
    try {
      await valueFormRef.value?.validate();
      await updateShopSpecValue({ ...editingValue });
      message.success('修改成功');
      showValueEdit.value = false;
      loadValues();
    } catch (e: any) {
      if (e?.message) message.error(e.message);
    }
  };

  // 删除规格值
  const removeValue = (item: ShopSpecValue) => {
    Modal.confirm({
      title: '提示',
      content: `确定要删除规格值「${item.specValue}」吗？`,
      maskClosable: true,
      onOk: async () => {
        try {
          const msg = await removeShopSpecValue(item.specValueId);
          message.success(msg);
          loadValues();
        } catch (e: any) {
          message.error(e.message || '删除失败');
        }
      }
    });
  };

  // 图片上传
  const handleImageUpload = async (file: File) => {
    try {
      const res = await uploadFile(file);
      editingValue.image = res.path;
      message.success('上传成功');
    } catch (e: any) {
      message.error(e.message || '上传失败');
    }
    return false; // 阻止 ant-design-vue 自动上传
  };
</script>

<style lang="less" scoped>
  .spec-value-panel {
    padding: 12px 16px 8px 40px;
    background: #fafafa;
    border-radius: 4px;

    .spec-value-header {
      margin-bottom: 10px;
      .label {
        font-weight: 500;
        font-size: 13px;
        color: rgba(0, 0, 0, 0.85);
      }
      .tip {
        margin-left: 10px;
        font-size: 12px;
        color: #999;
      }
    }

    .spec-value-body {
      .tags-wrap {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: center;
        min-height: 36px;
      }

      .spec-tag {
        cursor: pointer;
        font-size: 13px;
        padding: 4px 10px;
        display: inline-flex;
        align-items: center;
        gap: 4px;

        &:hover {
          border-color: #1890ff;
          color: #1890ff;
        }

        .tag-img-wrap {
          display: inline-flex;
          align-items: center;
          .tag-img {
            width: 18px;
            height: 18px;
            border-radius: 2px;
            object-fit: cover;
          }
        }

        .tag-sort {
          font-size: 11px;
          color: #999;
          margin-left: 2px;
          background: #f0f0f0;
          border-radius: 2px;
          padding: 0 3px;
        }
      }

      .add-tag {
        cursor: pointer;
        border-style: dashed;
        color: #1890ff;
        border-color: #1890ff;
        background: #e6f7ff;
        font-size: 13px;
        padding: 4px 10px;

        &:hover {
          background: #bae7ff;
        }
      }

      .tag-input {
        width: 120px;
        font-size: 13px;
      }
    }
  }

  .value-image-row {
    display: flex;
    align-items: center;
  }
</style>
