<template>
  <el-dialog
    :title="isEdit ? '编辑积分商品' : '已选择商品'"
    :visible.sync="visible"
    width="600px"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 商品信息显示 -->
    <div class="selected-product">
      <div class="product-info">
        <div class="info-item">
          <span class="label">商品ID：</span>
          <span class="value">{{ productData.productId }}</span>
        </div>
        <div class="info-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ productData.productName }}</span>
        </div>
        <div class="info-item">
          <span class="label">归属摊位：</span>
          <span class="value">{{ productData.shopName }}</span>
        </div>
        <div class="info-item">
          <span class="label">规格名称：</span>
          <span class="value">{{ productData.attributeValue }}</span>
        </div>
        <div class="info-item">
          <span class="label">SKU-ID：</span>
          <span class="value">{{ productData.productSpecId }}</span>
        </div>
        <div class="info-item">
          <span class="label">商品原价：</span>
          <span class="value">¥{{ productData.marketPrice }}</span>
        </div>
        <div class="info-item" v-if="isEdit">
          <span class="label">当前剩余库存：</span>
          <span class="value">{{ productData.surplusInventory }}</span>
        </div>
      </div>
    </div>

    <!-- 配置表单 -->
    <el-form
      ref="configForm"
      :model="configForm"
      :rules="configRules"
      label-width="140px"
      style="margin-top: 20px"
    >
      <el-form-item
        :label="isEdit ? '添加库存(负数代表减少库存)' : '库存设置'"
        prop="exchangeInventory"
        required
      >
        <div class="inventory-input">
          <el-button
            @click="decreaseInventory"
            :disabled="!isEdit && configForm.exchangeInventory <= 1"
            >-</el-button
          >
          <el-input-number
            v-model="configForm.exchangeInventory"
            :min="isEdit ? -99999 : 1"
            :max="99999"
            controls-position="right"
            style="width: 200px; margin: 0 10px"
          ></el-input-number>
          <el-button @click="increaseInventory">+</el-button>
        </div>
      </el-form-item>

      <el-form-item label="积分类型" prop="exchangePointsType" required>
        <el-radio-group v-model="configForm.exchangePointsType">
          <el-radio :label="2">积分优惠购</el-radio>
          <el-radio :label="1">积分换购</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="configForm.exchangePointsType === 1"
        label="兑换所需积分设置"
        prop="exchangeRequiredPoints"
        required
      >
        <div class="points-input">
          <el-button
            @click="decreasePoints"
            :disabled="configForm.exchangeRequiredPoints <= 1"
            >-</el-button
          >
          <el-input-number
            v-model="configForm.exchangeRequiredPoints"
            :min="1"
            :max="99999"
            controls-position="right"
            style="width: 200px; margin: 0 10px"
          ></el-input-number>
          <el-button @click="increasePoints">+</el-button>
        </div>
      </el-form-item>

      <el-form-item
        v-if="configForm.exchangePointsType === 2"
        label="优惠购所需积分"
        prop="exchangeRequiredPoints"
        required
      >
        <div class="points-input">
          <el-button
            @click="decreasePoints"
            :disabled="configForm.exchangeRequiredPoints <= 1"
            >-</el-button
          >
          <el-input-number
            v-model="configForm.exchangeRequiredPoints"
            :min="1"
            :max="99999"
            controls-position="right"
            style="width: 200px; margin: 0 10px"
          ></el-input-number>
          <el-button @click="increasePoints">+</el-button>
        </div>
      </el-form-item>

      <el-form-item
        v-if="configForm.exchangePointsType === 2"
        label="优惠购商品价格"
        prop="exchangeRequiredAmount"
        required
      >
        <el-input
          v-model="configForm.exchangeRequiredAmount"
          placeholder="请输入优惠购价格"
          style="width: 200px"
        ></el-input>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? "保存" : "确认" }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "PointsProductConfig",
  data() {
    return {
      visible: false,
      isEdit: false,
      submitting: false,
      productData: {},
      configForm: {
        id: undefined,
        shopId: undefined,
        productId: undefined,
        productSpecId: undefined,
        exchangeRequiredPoints: 1,
        exchangeInventory: 10,
        exchangePointsType: 1, // 1: 积分换购, 2: 积分优惠购
        exchangeRequiredAmount: ""
      },
      configRules: {
        exchangeRequiredPoints: [
          { required: true, message: "请设置所需积分", trigger: "blur" }
        ],
        exchangeInventory: [
          { required: true, message: "请设置库存", trigger: "blur" }
        ],
        exchangePointsType: [
          { required: true, message: "请选择积分类型", trigger: "change" }
        ],
        exchangeRequiredAmount: [
          {
            required: true,
            message: "请输入优惠购价格",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.configForm.exchangePointsType === 2 && !value) {
                callback(new Error("请输入优惠购价格"));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },

  methods: {
    show(productData, editData = null, exchangeType = 1) {
      this.visible = true;
      this.isEdit = !!editData;
      this.productData = productData;

      if (editData) {
        // 编辑模式，填充现有数据
        this.configForm = {
          id: editData.id || undefined,
          shopId: editData.shopId || undefined,
          productId: editData.productId || undefined,
          productSpecId: editData.productSpecId || undefined,
          exchangeRequiredPoints: editData.exchangeRequiredPoints || 1,
          exchangeInventory: 0, // 编辑模式下默认为0，表示增加库存
          exchangePointsType: editData.exchangePointsType || 1,
          exchangeRequiredAmount: editData.exchangeRequiredAmount || ""
        };
      } else {
        // 新增模式，使用默认值
        this.configForm = {
          id: undefined,
          shopId: productData.shopId || undefined,
          productId: productData.productId || undefined,
          productSpecId: productData.id || undefined, // 使用规格ID
          exchangeRequiredPoints: 1,
          exchangeInventory: 10,
          exchangePointsType: exchangeType, // 使用传入的积分类型
          exchangeRequiredAmount: ""
        };
      }
    },
    handleClose() {
      this.visible = false;
      this.resetForm();
    },
    resetForm() {
      this.productData = {};
      this.configForm = {
        id: undefined,
        shopId: undefined,
        productId: undefined,
        productSpecId: undefined,
        exchangeRequiredPoints: 1,
        exchangeInventory: 10,
        exchangePointsType: 1,
        exchangeRequiredAmount: ""
      };
      this.isEdit = false;
      this.$refs.configForm && this.$refs.configForm.clearValidate();
    },
    handleSubmit() {
      this.$refs.configForm.validate(valid => {
        if (valid) {
          this.submitting = true;

          let submitData;
          if (this.isEdit) {
            // 编辑模式使用新的参数格式
            submitData = {
              id: this.configForm.id,
              exchangeRequiredPoints: this.configForm.exchangeRequiredPoints,
              increaseInventory: this.configForm.exchangeInventory, // 增加库存
              exchangeRequiredAmount:
                this.configForm.exchangeRequiredAmount || 0,
              enable: true // 默认启用
            };
          } else {
            // 新增模式使用原有格式
            submitData = {
              ...this.configForm
            };
          }
          console.log(submitData);

          // 根据是否编辑模式调用不同的API
          const apiCall = this.isEdit
            ? this.$api.marketing.updateMembershipPointsProduct(submitData)
            : this.$api.marketing.addMembershipPointsProduct(submitData);

          apiCall
            .then(res => {
              this.$message.success(this.isEdit ? "编辑成功" : "添加成功");
              this.submitting = false;
              this.$emit("success", submitData);
              this.handleClose();
            })
            .catch(err => {
              console.error("提交积分商品配置失败:", err);
              this.$message.error(this.isEdit ? "编辑失败" : "添加失败");
              this.submitting = false;
            });
        }
      });
    },
    decreasePoints() {
      if (this.configForm.exchangeRequiredPoints > 1) {
        this.configForm.exchangeRequiredPoints--;
      }
    },
    increasePoints() {
      this.configForm.exchangeRequiredPoints++;
    },
    decreaseInventory() {
      if (this.isEdit) {
        this.configForm.exchangeInventory--;
      } else if (this.configForm.exchangeInventory > 1) {
        this.configForm.exchangeInventory--;
      }
    },
    increaseInventory() {
      this.configForm.exchangeInventory++;
    },
    decreaseLimitQuantity() {
      if (this.configForm.exchangeRestrictions > 0) {
        this.configForm.exchangeRestrictions--;
      }
    },
    increaseLimitQuantity() {
      this.configForm.exchangeRestrictions++;
    }
  }
};
</script>

<style lang="scss" scoped>
.selected-product {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.product-info {
  .info-item {
    display: flex;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #606266;
      min-width: 80px;
    }

    .value {
      color: #303133;
      font-weight: 500;
    }
  }
}

.points-input,
.inventory-input,
.limit-input {
  display: flex;
  align-items: center;

  .el-button {
    width: 40px;
    height: 40px;
  }
}

.limit-input {
  .el-select {
    margin-left: 10px;
  }
}
</style>
