<template>
  <div class="goods-spec-editor">
    <!-- 规格名称设置 -->
    <div class="spec-names">
      <h4>规格设置</h4>
      <div v-for="(spec, index) in specNames" :key="index" class="spec-name-item">
        <el-input
          v-model="spec.name"
          placeholder="请输入规格名称，如：颜色、尺寸"
          style="width: 200px; margin-right: 10px"
          @input="updateSpecCombinations"
        />
        <el-button v-if="specNames.length > 1" type="danger" text @click="removeSpecName(index)">
          删除
        </el-button>
      </div>
      <el-button v-if="specNames.length < 3" type="primary" text @click="addSpecName">
        + 添加规格
      </el-button>
    </div>

    <!-- 规格值设置 -->
    <div v-if="specNames.length > 0" class="spec-values">
      <h4>规格值设置</h4>
      <div v-for="(spec, specIndex) in specNames" :key="specIndex" class="spec-value-group">
        <div class="spec-value-label">{{ spec.name || `规格${specIndex + 1}` }}：</div>
        <div class="spec-value-list">
          <el-tag
            v-for="(value, valueIndex) in spec.values"
            :key="valueIndex"
            closable
            @close="removeSpecValue(specIndex, valueIndex)"
            style="margin-right: 8px; margin-bottom: 8px"
          >
            {{ value }}
          </el-tag>
          <el-input
            v-if="spec.inputVisible"
            ref="specValueInput"
            v-model="spec.inputValue"
            size="small"
            style="width: 100px"
            @keyup.enter="confirmSpecValue(specIndex)"
            @blur="confirmSpecValue(specIndex)"
          />
          <el-button v-else size="small" text @click="showSpecValueInput(specIndex)">
            + 添加规格值
          </el-button>
        </div>
      </div>
    </div>

    <!-- 规格组合表格 -->
    <div v-if="specCombinations.length > 0" class="spec-combinations">
      <h4>规格组合</h4>
      <el-table :data="specCombinations" border style="width: 100%">
        <el-table-column
          v-for="(spec, index) in specNames"
          :key="index"
          :prop="`spec_${index}`"
          :label="spec.name || `规格${index + 1}`"
          width="120"
        />
        <el-table-column label="价格" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.price"
              type="number"
              min="0"
              step="0.01"
              placeholder="0.00"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100">
          <template #default="scope">
            <el-input
              v-model="scope.row.stock"
              type="number"
              min="0"
              placeholder="0"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="重量(kg)" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.weight"
              type="number"
              min="0"
              step="0.01"
              placeholder="0.00"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="SKU编码" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.sku" placeholder="请输入SKU" size="small" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

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

  export default {
    name: 'GoodsSpecEditor',
  };
</script>

<script setup>
  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => [],
    },
  });

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

  // 规格名称
  const specNames = ref([{ name: '', values: [], inputVisible: false, inputValue: '' }]);

  // 规格组合
  const specCombinations = ref([]);

  // 规格值输入框引用
  const specValueInput = ref();

  // 添加规格名称
  const addSpecName = () => {
    if (specNames.value.length < 3) {
      specNames.value.push({
        name: '',
        values: [],
        inputVisible: false,
        inputValue: '',
      });
    }
  };

  // 删除规格名称
  const removeSpecName = (index) => {
    specNames.value.splice(index, 1);
    updateSpecCombinations();
  };

  // 显示规格值输入框
  const showSpecValueInput = (specIndex) => {
    specNames.value[specIndex].inputVisible = true;
    nextTick(() => {
      specValueInput.value?.[specIndex]?.focus();
    });
  };

  // 确认添加规格值
  const confirmSpecValue = (specIndex) => {
    const spec = specNames.value[specIndex];
    const value = spec.inputValue.trim();

    if (value && !spec.values.includes(value)) {
      spec.values.push(value);
      updateSpecCombinations();
    }

    spec.inputVisible = false;
    spec.inputValue = '';
  };

  // 删除规格值
  const removeSpecValue = (specIndex, valueIndex) => {
    specNames.value[specIndex].values.splice(valueIndex, 1);
    updateSpecCombinations();
  };

  // 更新规格组合
  const updateSpecCombinations = () => {
    const validSpecs = specNames.value.filter((spec) => spec.name.trim() && spec.values.length > 0);

    if (validSpecs.length === 0) {
      specCombinations.value = [];
      emit('update:modelValue', []);
      return;
    }

    // 生成所有可能的组合
    const combinations = generateCombinations(validSpecs);

    // 保留已有的价格、库存等信息
    const existingData = new Map();
    specCombinations.value.forEach((item) => {
      const key = validSpecs.map((_, index) => item[`spec_${index}`]).join('|');
      existingData.set(key, {
        price: item.price,
        stock: item.stock,
        weight: item.weight,
        sku: item.sku,
      });
    });

    specCombinations.value = combinations.map((combination) => {
      const key = combination.join('|');
      const existing = existingData.get(key) || {};

      const item = {
        price: existing.price || '',
        stock: existing.stock || '',
        weight: existing.weight || '',
        sku: existing.sku || '',
      };

      // 添加规格值
      combination.forEach((value, index) => {
        item[`spec_${index}`] = value;
      });

      return item;
    });

    // 发送更新事件
    emit('update:modelValue', specCombinations.value);
  };

  // 生成规格组合
  const generateCombinations = (specs) => {
    if (specs.length === 0) return [];
    if (specs.length === 1) return specs[0].values.map((v) => [v]);

    const result = [];
    const generate = (current, remaining) => {
      if (remaining.length === 0) {
        result.push([...current]);
        return;
      }

      const [first, ...rest] = remaining;
      first.values.forEach((value) => {
        generate([...current, value], rest);
      });
    };

    generate([], specs);
    return result;
  };

  // 监听外部数据变化
  watch(
    () => props.modelValue,
    (newValue) => {
      if (newValue && newValue.length > 0) {
        // 从外部数据恢复规格设置
        // 这里可以根据需要实现数据恢复逻辑
      }
    },
    { immediate: true },
  );

  // 监听规格组合变化
  watch(
    specCombinations,
    (newValue) => {
      emit('update:modelValue', newValue);
    },
    { deep: true },
  );
</script>

<style lang="scss" scoped>
  .goods-spec-editor {
    .spec-names {
      margin-bottom: 30px;

      h4 {
        margin: 0 0 15px 0;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .spec-name-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
      }
    }

    .spec-values {
      margin-bottom: 30px;

      h4 {
        margin: 0 0 15px 0;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .spec-value-group {
        display: flex;
        align-items: flex-start;
        margin-bottom: 15px;

        .spec-value-label {
          width: 100px;
          font-weight: 500;
          color: #606266;
          line-height: 32px;
          flex-shrink: 0;
        }

        .spec-value-list {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          align-items: center;
        }
      }
    }

    .spec-combinations {
      h4 {
        margin: 0 0 15px 0;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
</style>
