<template>
  <!-- 商品基本信息表单 -->
  <div style="margin-top: 50px">
    <el-form
      :model="value"
      :rules="rules"
      ref="productInfoForm"
      label-width="120px"
      class="form-inner-container"
      size="small"
    >
      <!-- 商品分类选择 -->
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          v-model="selectProductCateValue"
          :options="productCateOptions"
        ></el-cascader>
      </el-form-item>

      <!-- 商品名称输入框 -->
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="value.name"></el-input>
      </el-form-item>

      <!-- 商品副标题输入框 -->
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="value.subTitle"></el-input>
      </el-form-item>

      <!-- 商品品牌选择框 -->
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select
          v-model="value.brandId"
          @change="handleBrandChange"
          placeholder="请选择品牌"
        >
          <el-option
            v-for="item in brandOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 商品介绍文本域 -->
      <el-form-item label="商品介绍：">
        <el-input
          :autoSize="true"
          v-model="value.description"
          type="textarea"
          placeholder="请输入内容"
        ></el-input>
      </el-form-item>

      <!-- 商品货号 -->
      <el-form-item label="商品货号：">
        <el-input v-model="value.productSn"></el-input>
      </el-form-item>

      <!-- 商品售价 -->
      <el-form-item label="商品售价：">
        <el-input v-model="value.price"></el-input>
      </el-form-item>

      <!-- 市场价 -->
      <el-form-item label="市场价：">
        <el-input v-model="value.originalPrice"></el-input>
      </el-form-item>

      <!-- 商品库存 -->
      <el-form-item label="商品库存：">
        <el-input v-model="value.stock"></el-input>
      </el-form-item>

      <!-- 计量单位 -->
      <el-form-item label="计量单位：">
        <el-input v-model="value.unit"></el-input>
      </el-form-item>

      <!-- 商品重量 -->
      <el-form-item label="商品重量：">
        <el-input v-model="value.weight" style="width: 300px"></el-input>
        <span style="margin-left: 20px">克</span>
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序">
        <el-input v-model="value.sort"></el-input>
      </el-form-item>

      <!-- 下一步按钮 -->
      <el-form-item style="text-align: center">
        <el-button
          type="primary"
          size="medium"
          @click="handleNext('productInfoForm')"
        >
          下一步，填写商品促销
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { fetchListWithChildren } from '@/api/productCate'; // 获取商品分类
import { fetchList as fetchBrandList } from '@/api/brand'; // 获取品牌列表

export default {
  name: 'ProductInfoDetail', // 组件名称
  props: {
    value: Object, // 父组件传入的数据对象
    isEdit: {
      type: Boolean, // 是否为编辑模式
      default: false,
    },
  },
  data() {
    return {
      hasEditCreated: false, // 控制编辑状态是否初始化完成
      selectProductCateValue: [], // 选中的商品分类
      productCateOptions: [], // 商品分类级联数据
      brandOptions: [], // 品牌列表选项
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' },
        ],
        subTitle: [{ required: true, message: '请输入商品副标题', trigger: 'blur' }],
        productCategoryId: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
        brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 初始化分类列表和品牌列表
    this.getProductCateList();
    this.getBrandList();
  },
  computed: {
    // 监听商品ID
    productId() {
      return this.value.id;
    },
  },
  watch: {
    productId(newValue) {
      if (!this.isEdit || this.hasEditCreated || !newValue) return;
      this.handleEditCreated();
    },
    selectProductCateValue(newValue) {
      // 选中分类时，设置对应的分类ID和分类名称
      if (newValue && newValue.length === 2) {
        this.value.productCategoryId = newValue[1];
        this.value.productCategoryName = this.getCateNameById(this.value.productCategoryId);
      } else {
        this.value.productCategoryId = null;
        this.value.productCategoryName = null;
      }
    },
  },
  methods: {
    // 编辑模式下初始化商品分类
    handleEditCreated() {
      if (this.value.productCategoryId != null) {
        this.selectProductCateValue = [
          this.value.cateParentId,
          this.value.productCategoryId,
        ];
      }
      this.hasEditCreated = true;
    },

    // 获取商品分类列表
    getProductCateList() {
      fetchListWithChildren().then((response) => {
        let list = response.data;
        this.productCateOptions = list.map((item) => ({
          label: item.name,
          value: item.id,
          children: item.children?.map((child) => ({
            label: child.name,
            value: child.id,
          })),
        }));
      });
    },

    // 获取品牌列表
    getBrandList() {
      fetchBrandList({ pageNum: 1, pageSize: 100 }).then((response) => {
        this.brandOptions = response.data.list.map((item) => ({
          label: item.name,
          value: item.id,
        }));
      });
    },

    // 根据分类ID获取分类名称
    getCateNameById(id) {
      for (const parent of this.productCateOptions) {
        for (const child of parent.children || []) {
          if (child.value === id) {
            return child.label;
          }
        }
      }
      return null;
    },

    // 下一步验证表单数据
    handleNext(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('nextStep'); // 触发下一步事件
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000,
          });
        }
      });
    },

    // 处理品牌选择变化
    handleBrandChange(val) {
      const selectedBrand = this.brandOptions.find(
        (item) => item.value === val
      );
      this.value.brandName = selectedBrand ? selectedBrand.label : '';
    },
  },
};
</script>

<style scoped>
/* 表单样式居中 */
.form-inner-container {
  max-width: 600px;
  margin: 0 auto;
}
</style>
