<template>
  <el-container class="goods-edit-new">
    <el-main>
      <!-- 步骤进度条 -->
      <div class="step-progress">
        <el-steps :active="currentStep" align-center>
          <el-step title="商品信息" :status="getStepStatus(0)"></el-step>
          <el-step title="商品属性" :status="getStepStatus(1)"></el-step>
          <el-step title="提交" :status="getStepStatus(2)"></el-step>
        </el-steps>
      </div>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 第一步：商品信息 -->
        <div v-show="currentStep === 0" class="step-panel">
          <el-form ref="basicFormRef" :model="formData" :rules="basicRules" label-width="120px">
            <el-row :gutter="40">
              <!-- 左侧表单 -->
              <el-col :span="14">
                <el-form-item label="商品分类" prop="category_id" required>
                  <el-select
                    v-model="formData.category_id"
                    placeholder="请选择商品分类"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="category in categoryOptions"
                      :key="category.id"
                      :label="category.name"
                      :value="category.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="商品名称" prop="title" required>
                  <el-input
                    v-model="formData.title"
                    placeholder="请输入商品名称（限100字符）"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item label="副标题" prop="subtitle">
                  <el-input
                    v-model="formData.subtitle"
                    placeholder="请输入副标题（限50字符）"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item label="商品品牌" prop="brand" required>
                  <el-input v-model="formData.brand" placeholder="请输入商品品牌" />
                </el-form-item>

                <el-form-item label="商品介绍" prop="description">
                  <el-input
                    v-model="formData.description"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入商品介绍（限500字符）"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item label="运费模板" prop="freight_template" required>
                  <el-select
                    v-model="formData.freight_template"
                    placeholder="请选择运费模板"
                    style="width: 100%"
                  >
                    <el-option label="包邮" value="free" />
                  </el-select>
                </el-form-item>

                <el-form-item label="商品货号" prop="goods_no" required>
                  <el-input v-model="formData.goods_no" placeholder="请输入商品货号" />
                  <div class="form-tip">如果您不输入商品货号，系统将自动生成一个唯一的货号</div>
                </el-form-item>

                <el-form-item label="商品售价" prop="price" required>
                  <el-input
                    v-model="formData.price"
                    placeholder="请输入商品售价"
                    type="number"
                    min="0"
                    step="0.01"
                  >
                    <template #append>৳</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="市场价" prop="market_price">
                  <el-input
                    v-model="formData.market_price"
                    placeholder="请输入市场价"
                    type="number"
                    min="0"
                    step="0.01"
                  >
                    <template #append>৳</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="商品库存" prop="stock" required>
                  <el-input
                    v-model="formData.stock"
                    placeholder="请输入商品库存"
                    type="number"
                    min="0"
                  />
                  <div class="form-tip"
                    >该设置只对单品有效，当商品存在多规格货品时为不可编辑状态，库存数值取决于货品数量</div
                  >
                </el-form-item>

                <el-form-item label="库存预警值" prop="stock_warning">
                  <el-input
                    v-model="formData.stock_warning"
                    placeholder="请输入库存预警值"
                    type="number"
                    min="0"
                  />
                </el-form-item>

                <el-form-item label="商品状态" prop="status" required>
                  <el-radio-group v-model="formData.status">
                    <el-radio label="up">上架</el-radio>
                    <el-radio label="down">下架</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="商品供应商" prop="supplier" required>
                  <el-input v-model="formData.supplier" placeholder="请输入商品供应商" />
                </el-form-item>
              </el-col>

              <!-- 右侧图片上传 -->
              <el-col :span="10">
                <el-form-item label="商品主图" prop="images" required>
                  <sa-upload-image
                    v-model="formData.images"
                    :max-count="5"
                    :accept="['jpg', 'jpeg', 'png']"
                    :max-size="5"
                    :direct-upload="true"
                    :size="100"
                    placeholder="上传商品主图"
                  />
                </el-form-item>

                <el-form-item label="白底图" prop="white_bg_image">
                  <sa-upload-image
                    v-model="formData.white_bg_image"
                    :max-count="1"
                    :accept="['jpg', 'jpeg', 'png']"
                    :max-size="5"
                    :direct-upload="true"
                    :size="100"
                    placeholder="上传白底图"
                  />
                </el-form-item>

                <el-form-item label="详情图" prop="detail_images" required>
                  <sa-upload-image
                    v-model="formData.detail_images"
                    :max-count="10"
                    :accept="['jpg', 'jpeg', 'png']"
                    :max-size="5"
                    :direct-upload="true"
                    :size="100"
                    placeholder="上传详情图"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 第二步：商品属性 -->
        <div v-show="currentStep === 1" class="">
          <el-form ref="attrFormRef" :model="formData" :rules="attrRules" label-width="120px">
            <!-- 多规格设置 -->
            <el-card class="spec-card">
              <template #header>
                <div class="card-header">
                  <span>商品规格设置</span>
                </div>
              </template>

              <!-- 操作 -->
              <div class="sku-wrap">
                <div class="sku" v-for="(s, k) in formData.skus" :key="k">
                  <div class="sku-key sa-flex sa-row-between">
                    <div class="sa-flex">
                      <div class="sa-m-r-16">规格名称</div>
                      <el-input
                        v-model="s.name"
                        placeholder="请输入规格名称"
                        class="sku-key-input"
                        @input="buildSkuPriceTable"
                      ></el-input>
                    </div>
                    <el-icon @click="deleteMainSku(k)" class="sku-key-icon">
                      <CircleCloseFilled />
                    </el-icon>
                  </div>
                  <div class="sku-value sa-flex sa-flex-wrap">
                    <div class="sku-value-title sa-m-r-16 sa-m-b-16 sa-flex"> 规格值 </div>
                    <div v-for="(sc, c) in s.children" :key="c" class="sku-value-box sa-m-b-16">
                      <el-input
                        v-model="sc.name"
                        placeholder="请输入规格值"
                        class="sku-value-input"
                        @input="buildSkuPriceTable"
                      ></el-input>
                      <el-icon @click="deleteChildrenSku(k, c)" class="sku-value-icon">
                        <CircleCloseFilled />
                      </el-icon>
                    </div>
                    <div
                      @click="addChildrenSku(k)"
                      class="sku-value-add sa-m-r-24 sa-m-b-16 sa-flex cursor-pointer"
                    >
                      添加规格值
                    </div>
                  </div>
                </div>
                <div class="sku-tools sa-flex">
                  <el-button type="primary" class="add" @click="addMainSku">+ 添加规格</el-button>
                </div>
              </div>

              <!-- 批量设置 -->
              <div class="sa-m-t-20" v-if="formData.sku_prices.length > 0">
                <el-form-item label="批量设置" label-width="80px">
                  <div class="sku sa-m-r-20" v-for="(item, index) in formData.skus" :key="index">
                    <el-select
                      v-model="item.batchId"
                      placeholder="请选择规格"
                      class="sa-w-150"
                      clearable
                    >
                      <template v-for="(citem, cindex) in item.children">
                        <el-option
                          :key="cindex"
                          :label="citem.name"
                          :value="citem.temp_id"
                          v-if="citem.temp_id && citem.name"
                        ></el-option>
                      </template>
                    </el-select>
                  </div>
                  <div class="warning-title" style="margin-left: 8px">
                    未选择规格默认为全选批量设置
                  </div>
                </el-form-item>
                <div class="sa-flex">
                  <el-input
                    v-model="allEditObj.price"
                    placeholder="请输入售价(৳)"
                    class="sa-w-200 sa-m-r-10"
                  >
                    <template #prepend>售价(৳)</template>
                  </el-input>
                  <el-input
                    v-model="allEditObj.stock"
                    placeholder="请输入库存(件)"
                    class="sa-w-200 sa-m-r-10"
                  >
                    <template #prepend>库存(件)</template>
                  </el-input>
                  <el-input
                    v-model="allEditObj.stock_warning"
                    placeholder="请输入库存预警值(件)"
                    class="sa-w-200 sa-m-r-10"
                  >
                    <template #prepend>库存预警值(件)</template>
                  </el-input>
                  <el-button type="primary" @click="batchEdit">批量设置</el-button>
                </div>
              </div>

              <!-- 表格 -->
              <div class="sku-table-wrap sa-m-b-20">
                <table class="sku-table" rules="all">
                  <thead>
                    <tr>
                      <template v-for="(item, i) in formData.skus" :key="i">
                        <th v-if="item.children.length">{{ item.name }}</th>
                      </template>
                      <th>图片</th>
                      <th><span class="required">*</span>销售价格(৳)</th>
                      <th><span class="required">*</span>商品库存</th>
                      <th>库存预警值</th>
                      <th>SKU编码</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, i) in formData.sku_prices" :key="i">
                      <template v-for="(v, j) in item.goods_sku_text" :key="j">
                        <td>
                          <span class="th-center">{{ v }}</span>
                        </td>
                      </template>
                      <td class="image">
                        <sa-upload-image
                          v-model="item.imageList"
                          :max-count="1"
                          :accept="['jpg', 'jpeg', 'png']"
                          :max-size="5"
                          :direct-upload="true"
                          :size="30"
                          :show-tip="false"
                          :compact="true"
                          placeholder=""
                        />
                      </td>
                      <td>
                        <el-input
                          v-model="item.price"
                          placeholder="请输入价格"
                          size="small"
                          type="number"
                          :step="0.01"
                          :min="0"
                          :precision="2"
                          :class="{ 'is-error': !item.price || item.price <= 0 }"
                        ></el-input>
                      </td>
                      <td class="stock">
                        <el-input
                          v-model="item.stock"
                          placeholder="请输入库存"
                          size="small"
                          type="number"
                          :step="1"
                          :min="0"
                          :class="{ 'is-error': !item.stock || item.stock < 0 }"
                        ></el-input>
                      </td>
                      <td class="stock_warning">
                        <el-input
                          v-model="item.stock_warning"
                          placeholder="请输入预警值"
                          size="small"
                          type="number"
                          :step="1"
                          :min="0"
                        ></el-input>
                      </td>
                      <td class="sn">
                        <el-input
                          v-model="item.sn"
                          placeholder="请输入SKU编码"
                          size="small"
                        ></el-input>
                      </td>
                      <td>
                        <el-button type="danger" size="small" text @click="deleteSkuPrice(i)"
                          >删除</el-button
                        >
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </el-card>
          </el-form>
        </div>

        <!-- 第三步：提交结果 -->
        <div v-show="currentStep === 2" class="step-panel submit-panel">
          <div class="submit-result">
            <div v-if="submitSuccess" class="success-content">
              <el-icon class="success-icon" color="#67C23A" :size="80">
                <CircleCheck />
              </el-icon>
              <h3 class="mt-20">
                {{ isEdit ? '保存成功' : '商品添加成功，请等上架' }}
              </h3>
              <div v-if="!isEdit" class="action-buttons mt-30">
                <el-button type="primary" @click="continueAction"> 继续添加 </el-button>
              </div>
            </div>
            <div v-else class="loading-content">
              <el-icon class="loading-icon" :size="80">
                <Loading />
              </el-icon>
              <h3>正在保存商品...</h3>
              <p>请稍候，系统正在处理您的请求</p>
            </div>
          </div>
        </div>
      </div>
    </el-main>

    <!-- 操作按钮 -->
    <el-footer class="sa-footer--submit">
      <template v-if="currentStep < 2">
        <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="nextStep" :loading="currentStep === 1 && submitLoading">
          {{ currentStep === 1 ? '提交' : '下一步' }}
        </el-button>
      </template>
      <template v-if="currentStep === 2">
        <el-button @click="closeModal">关闭</el-button>
      </template>
    </el-footer>
  </el-container>
</template>

<script>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { CircleCheck, CircleCloseFilled, Edit, Loading } from '@element-plus/icons-vue';

  import { api } from '../goods.service';

  export default {
    name: 'GoodsEditNew',
    components: {
      CircleCheck,
      CircleCloseFilled,
      Edit,
      Loading,
    },
  };
</script>

<script setup>
  const props = defineProps({
    modal: {
      type: Object,
      default: () => ({}),
    },
  });

  const emit = defineEmits(['success', 'modalCallBack']);

  // 当前步骤
  const currentStep = ref(0);

  // 是否为编辑模式
  const isEdit = computed(() => props.modal?.params?.type === 'edit');

  // 表单引用
  const basicFormRef = ref();
  const attrFormRef = ref();

  // 表单数据
  const formData = reactive({
    // 基本信息
    category_id: '',
    title: '',
    subtitle: '',
    brand: '',
    description: '',
    freight_template: 'free',
    goods_no: '',
    price: '',
    market_price: '',
    stock: '',
    stock_warning: '',
    status: 'up',
    supplier: '',

    // 图片
    images: [],
    white_bg_image: [],
    detail_images: [],

    // 规格
    has_spec: true, // 默认为多规格
    skus: [
      {
        id: 0,
        temp_id: 1,
        name: '',
        batchId: '',
        pid: 0,
        children: [],
      },
    ],
    sku_prices: [],
  });

  // 分类选项
  const categoryOptions = ref([]);

  // 表单验证规则
  const basicRules = {
    category_id: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
    title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    brand: [{ required: true, message: '请输入商品品牌', trigger: 'blur' }],
    freight_template: [{ required: true, message: '请选择运费模板', trigger: 'change' }],
    goods_no: [{ required: true, message: '请输入商品货号', trigger: 'blur' }],
    price: [{ required: true, message: '请输入商品售价', trigger: 'blur' }],
    stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
    status: [{ required: true, message: '请选择商品状态', trigger: 'change' }],
    supplier: [{ required: true, message: '请输入商品供应商', trigger: 'blur' }],
    images: [{ required: true, message: '请上传商品主图', trigger: 'change' }],
    detail_images: [{ required: true, message: '请上传商品详情图', trigger: 'change' }],
  };

  const attrRules = {
    spec_price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
    spec_stock: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  };

  // 获取步骤状态
  const getStepStatus = (step) => {
    if (step < currentStep.value) return 'finish';
    if (step === currentStep.value) return 'process';
    return 'wait';
  };

  // 多规格相关变量和函数
  const countId = ref(2);
  const childrenModal = [];
  const isResetSku = ref(0);

  // 批量操作相关变量
  const allEditObj = ref({
    price: 0,
    stock: 0,
    stock_warning: 0,
  });

  // 添加主规格
  const addMainSku = () => {
    formData.skus.push({
      id: 0,
      temp_id: countId.value++,
      name: '',
      batchId: '',
      pid: 0,
      children: [],
    });
    buildSkuPriceTable();
  };

  // 删除主规格
  const deleteMainSku = (k) => {
    let data = formData.skus[k];

    // 删除主规格
    formData.skus.splice(k, 1);

    // 如果当前删除的主规格存在子规格，则清空 skuPrice
    if (data.children.length > 0) {
      formData.sku_prices = [];
      isResetSku.value = 1;
    }
    buildSkuPriceTable();
  };

  // 添加子规格
  const addChildrenSku = (k) => {
    let isExist = false;
    formData.skus[k].children.forEach((e) => {
      if (e.name == childrenModal[k] && e.name != '') {
        isExist = true;
      }
    });
    if (isExist) {
      ElMessage.warning('子规格已存在');
      return false;
    }

    formData.skus[k].children.push({
      id: 0,
      temp_id: countId.value++,
      name: childrenModal[k] || '',
      pid: formData.skus[k].id,
    });
    childrenModal[k] = '';

    // 如果是添加的第一个子规格，清空 skuPrice
    if (formData.skus[k].children.length == 1) {
      formData.sku_prices = [];
      isResetSku.value = 1;
    }
    buildSkuPriceTable();
  };

  // 删除子规格
  const deleteChildrenSku = (k, i) => {
    let data = formData.skus[k].children[i];
    formData.skus[k].children.splice(i, 1);

    // 查询 sku_prices 中包含被删除的子规格的项，然后移除
    let deleteArr = [];
    formData.sku_prices.forEach((item, index) => {
      item.goods_sku_text.forEach((e, idx) => {
        if (e == data.name) {
          deleteArr.push(index);
        }
      });
    });
    deleteArr.sort(function (a, b) {
      return b - a;
    });
    // 移除有相关子规格的项
    deleteArr.forEach((idx, e) => {
      formData.sku_prices.splice(idx, 1);
    });

    // 当前规格项，所有子规格都被删除，清空 sku_prices
    if (formData.skus[k].children.length <= 0) {
      formData.sku_prices = [];
      isResetSku.value = 1;
    }
    buildSkuPriceTable();
  };

  // 组成新的规格
  const buildSkuPriceTable = () => {
    let arr = [];
    // 遍历sku子规格生成新数组，然后执行递归笛卡尔积
    formData.skus.forEach((s1, k1) => {
      let children = s1.children;
      let childrenIdArray = [];
      if (children.length > 0) {
        children.forEach((s2, k2) => {
          childrenIdArray.push(s2.temp_id);
        });
        // 如果 children 子规格数量为 0,则不渲染当前规格
        arr.push(childrenIdArray);
      }
    });
    recursionSku(arr, 0, []);
  };

  // 递归找笛卡尔规格集合
  const recursionSku = (arr, k, temp) => {
    if (k == arr.length && k != 0) {
      let tempDetail = [];
      let tempDetailIds = [];
      temp.forEach((item, index) => {
        for (let sku of formData.skus) {
          for (let child of sku.children) {
            if (item == child.temp_id) {
              tempDetail.push(child.name);
              tempDetailIds.push(child.temp_id);
            }
          }
        }
      });
      let flag = false; // 默认添加新的
      for (let i = 0; i < formData.sku_prices.length; i++) {
        if (formData.sku_prices[i].goods_sku_temp_ids.join(',') == tempDetailIds.join(',')) {
          flag = i;
          break;
        }
      }

      if (flag === false) {
        formData.sku_prices.push({
          id: 0,
          temp_id: formData.sku_prices.length + 1,
          goods_sku_ids: '',
          goods_id: 0,
          weigh: 0,
          image: '',
          imageList: [],
          stock: 0,
          stock_warning: 0,
          price: 0,
          sn: '',
          goods_sku_text: tempDetail,
          goods_sku_temp_ids: tempDetailIds,
        });
      } else {
        formData.sku_prices[flag].goods_sku_text = tempDetail;
        formData.sku_prices[flag].goods_sku_temp_ids = tempDetailIds;
      }
      return;
    }
    if (arr.length) {
      for (let i = 0; i < arr[k].length; i++) {
        temp[k] = arr[k][i];
        recursionSku(arr, k + 1, temp);
      }
    }
  };

  // 批量操作
  const batchEdit = () => {
    const batchIds = formData.skus.map((item) => item.batchId).filter((item) => Boolean(item));
    formData.sku_prices.forEach((item) => {
      if (
        batchIds.length ? batchIds.every((citem) => item.goods_sku_temp_ids.includes(citem)) : true
      ) {
        const { price, stock, stock_warning } = allEditObj.value;
        if (price) item.price = price;
        if (stock) item.stock = stock;
        if (stock_warning) item.stock_warning = stock_warning;
      }
    });

    // 清空输入框
    allEditObj.value = {
      price: 0,
      stock: 0,
      stock_warning: 0,
    };

    // 清空选择的规格
    formData.skus.forEach((item) => {
      item.batchId = '';
    });

    ElMessage.success('批量设置成功');
  };

  // 删除规格组合
  const deleteSkuPrice = (index) => {
    formData.sku_prices.splice(index, 1);
    ElMessage.success('删除成功');
  };

  // SKU校验
  const validateSku = () => {
    if (formData.sku_prices.length === 0) {
      ElMessage.error('请先添加商品规格');
      return false;
    }

    for (let i = 0; i < formData.sku_prices.length; i++) {
      const item = formData.sku_prices[i];
      if (!item.price || item.price <= 0) {
        ElMessage.error(`第${i + 1}个规格的销售价格不能为空且必须大于0`);
        return false;
      }
      if (item.stock === null || item.stock === undefined || item.stock < 0) {
        ElMessage.error(`第${i + 1}个规格的商品库存不能为空且不能小于0`);
        return false;
      }
    }
    return true;
  };

  // 提交表单
  const submitLoading = ref(false);
  const submitError = ref('');
  const submitSuccess = ref(false);

  const submitForm = async () => {
    try {
      submitLoading.value = true;
      submitError.value = '';

      // 准备提交数据
      const submitData = {
        ...formData,
        sku_prices: formData.sku_prices.map((item) => ({
          ...item,
          image: item.imageList && item.imageList.length > 0 ? item.imageList[0] : '',
        })),
      };
      // 测试 需删除逻辑
      console.log(submitData);
      submitSuccess.value = true;
      currentStep.value = 2; // 跳转到成功页面
      return;

      // 调用API提交
      const response = await api.post('/admin/goods/save', submitData);

      if (response.code === 0) {
        submitSuccess.value = true;
        currentStep.value = 2; // 跳转到成功页面
        ElMessage.success('商品保存成功');
      } else {
        throw new Error(response.msg || '保存失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      submitError.value = error.message || '提交失败，请重试';
      ElMessage.error(submitError.value);
    } finally {
      submitLoading.value = false;
    }
  };

  // 下一步
  const nextStep = async () => {
    if (currentStep.value === 0) {
      // 验证基本信息
      const valid = await basicFormRef.value?.validate().catch(() => false);
      if (!valid) {
        ElMessage.error('请完善基本信息');
        return;
      }
      currentStep.value++;
    } else if (currentStep.value === 1) {
      // 验证SKU并提交
      if (!validateSku()) {
        return;
      }
      await submitForm();
    }
  };

  // 继续操作（只用于新增模式）
  const continueAction = () => {
    // 新增模式：重置表单继续添加
    resetForm();
    currentStep.value = 0;
    submitSuccess.value = false;
  };

  // 关闭弹窗
  const closeModal = () => {
    emit('modalCallBack', {
      event: 'confirm',
    });
  };

  // 重置表单
  const resetForm = () => {
    Object.assign(formData, {
      title: '',
      category_ids: [],
      brand: '',
      goods_no: '',
      supplier: '',
      images: [],
      white_bg_image: [],
      detail_images: [],
      has_spec: true,
      skus: [
        {
          id: 0,
          temp_id: 1,
          name: '',
          batchId: '',
          pid: 0,
          children: [],
        },
      ],
      sku_prices: [],
    });
  };

  // 上一步
  const prevStep = () => {
    if (currentStep.value > 0) {
      currentStep.value--;
    }
  };

  // 保存草稿
  const saveDraft = async () => {
    try {
      const data = { ...formData, status: 'draft' };
      // 调用保存接口
      await saveGoods(data);
      ElMessage.success('保存草稿成功');
      emit('modalCallBack', { event: 'confirm' });
    } catch (error) {
      ElMessage.error('保存失败：' + error.message);
    }
  };

  // 提交商品
  const submitGoods = async () => {
    try {
      const data = { ...formData };
      // 调用保存接口
      await saveGoods(data);
      ElMessage.success('商品上架成功');
      emit('modalCallBack', { event: 'confirm' });
    } catch (error) {
      ElMessage.error('提交失败：' + error.message);
    }
  };

  // 保存商品接口调用
  const saveGoods = async (data) => {
    try {
      const response = await api.goods.saveGoods(data);
      if (response.error === 0) {
        return response.data;
      } else {
        throw new Error(response.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存商品失败:', error);
      throw error;
    }
  };

  // 获取分类数据
  const getCategoryData = async () => {
    try {
      const response = await api.goods.getType();
      if (response.error === 0) {
        // 只使用一级分类
        categoryOptions.value = response.data.categories;
      }
    } catch (error) {
      console.error('获取分类失败:', error);
    }
  };

  // 初始化
  const init = () => {
    getCategoryData();
    if (props.modal?.params?.type === 'edit' && props.modal?.params?.id) {
      // 编辑模式，加载商品数据
      loadGoodsData(props.modal.params.id);
    }
  };

  // 加载商品数据
  const loadGoodsData = async (id) => {
    try {
      // 这里调用获取商品详情接口
      console.log('加载商品数据:', id);
      const response = await api.goods.getGoodsDetail(id);
      if (response.error === 0) {
        // 将数据填充到表单中
        Object.assign(formData, response.data);
      }
    } catch (error) {
      console.error('加载商品数据失败:', error);
    }
  };

  // 组件挂载时初始化
  onMounted(() => {
    init();
  });
</script>

<style lang="scss" scoped>
  .goods-edit-new {
    .el-main {
      padding: 20px;
      background: #f5f5f5;
      overflow-y: auto;
    }

    .step-progress {
      background: #fff;
      padding: 30px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .step-content {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      min-height: 500px;

      .step-panel {
        padding: 30px;
      }

      .upload-section {
        .upload-tip {
          margin-top: 8px;
          font-size: 12px;
          color: #999;
          line-height: 1.4;
        }
      }

      .spec-card {
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: 500;
        }

        .single-spec {
          padding: 20px 0;
        }

        .multi-spec {
          padding: 20px 0;
        }
      }

      .submit-panel {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 500px;

        .submit-success {
          text-align: center;

          .success-icon {
            margin-bottom: 20px;
          }

          h3 {
            margin: 0 0 10px 0;
            font-size: 20px;
            color: #303133;
          }

          p {
            margin: 0;
            color: #606266;
            font-size: 14px;
          }
        }
      }
    }
  }

  .batch-operations {
    margin: 16px 0;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .sku-wrap {
    width: 100%;
    border: 1px solid #d9d9d9;
    padding: 8px;
    box-sizing: border-box;
    .sku {
      width: 100%;
      min-height: 100px;
      .sku-key {
        width: 100%;
        height: 40px;
        color: var(--sa-subtitle);
        padding: 0 16px;
        background: var(--sa-table-header-bg);
        font-size: 14px;
        .sku-key-input {
          width: 120px;
        }
        .sku-key-icon {
          color: var(--el-color-primary);
        }
      }
      .sku-value {
        padding: 12px 0 0 30px;
        font-size: 14px;
        color: var(--sa-subtitle);
        .sku-value-title {
          height: 32px;
        }
        .sku-value-box {
          position: relative;
          margin-right: 24px;
          .sku-value-input {
            width: 104px;
          }
          .sku-value-icon {
            position: absolute;
            right: -8px;
            top: -8px;
            width: 16px;
            height: 16px;
            color: var(--el-color-primary);
          }
        }
        .sku-value-add {
          width: 104px;
          height: 32px;
          font-size: 14px;
          color: var(--el-color-primary);
        }
      }
    }
    .sku-tools {
      width: 100%;
      height: 40px;
      color: #434343;
      padding-left: 16px;
      background: var(--sa-table-header-bg);
      font-size: 12px;
    }
  }
  .alledit-input {
    margin-bottom: 10px;
  }

  .sku-table-wrap {
    width: 100%;
    overflow: auto;
    margin-top: 16px;
    .sku-table {
      width: 100%;
      border: 1px solid var(--sa-border);
      tbody {
        font-size: 12px;
      }
      th {
        font-size: 12px;
        color: var(--subtitle);
        height: 32px;
        line-height: 1;
        padding-left: 12px;
        box-sizing: border-box;
        text-align: left;
        .sku-table-header-title {
          margin-right: 10px;
        }
        .th-title {
          font-size: 12px;
          color: var(--subtitle);
          font-weight: bold;
        }
      }
      td {
        min-width: 88px;
        padding: 0 10px;
        height: 40px;
        box-sizing: border-box;
        &.image {
          min-width: 48px;
        }
        &.stock {
          min-width: 138px;
        }
        &.stock_warning {
          min-width: 168px;
          .sku-stock-switch {
            margin-right: 10px;
          }
        }
        &.sn {
          min-width: 116px;
        }
      }
    }
  }
  .batch-icon {
    width: 12px;
    height: 12px;
    margin-left: 5px;
    cursor: pointer;
  }

  // 弹窗中的特殊样式
  :deep(.sa-dialog) {
    .el-dialog__body {
      padding: 0;
      height: 80vh;
      overflow: hidden;
    }
  }

  // 表单样式优化
  :deep(.el-form-item) {
    margin-bottom: 24px;

    .el-form-item__label {
      font-weight: 500;
      color: #303133;
    }

    .form-tip {
      margin-top: 5px;
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
    }
  }

  :deep(.el-input) {
    .el-input__inner {
      border-radius: 6px;
    }
  }

  :deep(.el-select) {
    width: 100%;

    .el-input__inner {
      border-radius: 6px;
    }
  }

  :deep(.el-cascader) {
    .el-input__inner {
      border-radius: 6px;
    }
  }

  :deep(.el-textarea) {
    .el-textarea__inner {
      border-radius: 6px;
    }
  }

  // 步骤条样式
  :deep(.el-steps) {
    .el-step__title {
      font-size: 16px;
      font-weight: 500;
    }

    .el-step__description {
      font-size: 14px;
    }
  }

  // 卡片样式
  :deep(.el-card) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .el-card__header {
      padding: 20px;
      border-bottom: 1px solid #f0f0f0;
    }

    .el-card__body {
      padding: 20px;
    }
  }

  /* 必填项样式 */
  .required {
    color: #f56c6c;
    margin-right: 4px;
  }

  /* 错误状态样式 */
  .is-error .el-input__wrapper {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }

  /* 成功页面样式 */
  .submit-result {
    text-align: center;
    padding: 60px 20px;

    .success-content,
    .loading-content {
      .success-icon,
      .loading-icon {
        margin-bottom: 20px;
      }

      h3 {
        font-size: 24px;
        color: #303133;
        margin-bottom: 12px;
      }

      p {
        font-size: 14px;
        color: #909399;
        margin-bottom: 30px;
      }

      .action-buttons {
        .el-button {
          margin: 0 8px;
        }
      }
    }

    .loading-content {
      .loading-icon {
        animation: rotate 2s linear infinite;
      }
    }
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>
