<template>
  <div>
    <el-form :model="form" ref="form" :rules="rules" label-width="160px">
      <el-form-item label="规格项" v-if="skuTableList.length">
        <el-card
          shadow="hover"
          v-for="(v, i) in skuTableList"
          :key="v.id"
          class="box-card"
        >
          <div class="flex-between">
            <div>
              <span>规格:</span>
              <el-tag class="m-10">{{ v.name }}</el-tag>
            </div>
            <el-button
              type="text"
              @click="deleteSkuTable(i, v.id)"
              v-if="$route.query.type != 'show'"
              >删除规格项</el-button
            >
          </div>
          <el-checkbox-group
            v-model="skuTableObj[v.id]"
            @change="() => generateProducts()"
            :disabled="$route.query.type == 'show'"
          >
            <el-checkbox
              v-for="j in v.childrenList || []"
              :key="j.id"
              :label="j.id"
              >{{ j.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-card>
      </el-form-item>
      <el-form-item label="规格">
        <div style="margin-bottom: 20px" v-if="$route.query.type != 'show'">
          <el-button type="primary" @click="classifyClick"
            >选择规格项</el-button
          >
          <el-button type="primary" @click="addvalues">新增规格值</el-button>
        </div>
        <el-table
          :data="form.productSkuSetList || []"
          style="width: 100%"
          border
          class="specTable"
        >
          <el-table-column prop="skuSetName" label="规格" align="center">
          </el-table-column>
          <el-table-column prop="cover" label="图片" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.cover'"
                v-if="$route.query.type != 'show'"
              >
                <imageUpload
                  v-model="form.productSkuSetList[scope.$index].cover"
                  :limit="1"
                  :isShowTip="false"
                  :unique="form.productSkuSetList[scope.$index].skuHashCode"
                  :disabled="$route.query.type == 'show'"
                />
              </el-form-item>
              <imagePreview
                v-if="scope.row.cover && $route.query.type == 'show'"
                :src="scope.row.cover"
                width="100px"
                height="100px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="code" label="商品编码" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.code'"
                :rules="[
                  {
                    required: true,
                    message: '请输入商品编码',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input
                  v-model="form.productSkuSetList[scope.$index].code"
                  placeholder="请输入商品编码"
                ></el-input>
              </el-form-item>
              <span v-else>{{ scope.row.code }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="costPrice" label="成本价" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.costPrice'"
                :rules="[
                  {
                    required: true,
                    message: '请输入成本价',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].costPrice"
                  placeholder="请输入成本价"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.costPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="marketPrice" label="市场价格" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.marketPrice'"
                :rules="[
                  {
                    required: true,
                    message: '请输入市场价格',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].marketPrice"
                  placeholder="请输入市场价格"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.marketPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="salePrice" label="销售价格" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.salePrice'"
                :rules="[
                  {
                    required: true,
                    message: '请输入销售价格',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].salePrice"
                  placeholder="请输入销售价格"
                  controls-position="right"
                  :precision="2"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.salePrice }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="exchangePoint"
            label="兑换积分"
            align="center"
            v-if="productPaymentMode == '1'"
          >
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.exchangePoint'"
                :rules="[
                  {
                    required: true,
                    message: '请输入兑换积分',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].exchangePoint"
                  placeholder="请输入兑换积分"
                  controls-position="right"
                  :precision="0"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.exchangePoint }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(KG)" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.weight'"
                :rules="[
                  { required: true, message: '请输入重量', trigger: 'blur' },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].weight"
                  placeholder="请输入重量"
                  controls-position="right"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.weight }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="volume" label="体积(M3)" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.volume'"
                :rules="[
                  {
                    required: true,
                    message: '请输入体积(M3)',
                    trigger: 'blur',
                  },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].volume"
                  placeholder="请输入体积"
                  controls-position="right"
                  :min="0"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.volume }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" align="center">
            <template slot-scope="scope">
              <el-form-item
                label=""
                :prop="'productSkuSetList.' + scope.$index + '.stock'"
                :rules="[
                  { required: true, message: '请输入库存', trigger: 'blur' },
                ]"
                v-if="$route.query.type != 'show'"
              >
                <el-input-number
                  v-model="form.productSkuSetList[scope.$index].stock"
                  controls-position="right"
                  :precision="0"
                  :min="0"
                  placeholder="请输入库存"
                  style="width: 100%"
                ></el-input-number>
              </el-form-item>
              <span v-else>{{ scope.row.stock }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <shopSkuDialog
      ref="shopSkuDialogRef"
      :topList="[{ name: '顶级', id: 0 }, ...skusTreeList]"
      @submit="getSkusTree()"
    />

    <classifyDialog
      ref="classifyDialogRef"
      :list="skusTreeList"
      @setClassify="setClassify"
    />
  </div>
</template>
<script>
import { skusTree } from "@/api/shopSku.js";
import shopSkuDialog from "./shopSkuDialog.vue";
import classifyDialog from "./classifyDialog.vue";

export default {
  props: {
    productPaymentMode: {
      type: [String, Number],
      default: "0",
    },
  },
  components: { shopSkuDialog, classifyDialog },
  data() {
    return {
      skusTreeList: [],
      form: {
        productSkuSetList: [],
      },
      rules: {},
      skuTableObj: {}, // sku选中数据
      productSkuSetList: [],
      skuTableList: [],
    };
  },
  created() {
    this.getSkusTree();
  },

  methods: {
    getSkusTree(skuTableData) {
      skusTree().then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.skusTreeList = res.data || [];
          if(skuTableData) this.setSkuTableList(skuTableData);
        }
      });
    },
    addvalues() {
      this.$refs.shopSkuDialogRef.open();
    },
    classifyClick() {
      this.$refs.classifyDialogRef.open("3", this.skuTableList);
    },
    setClassify(val) {
      const objValue = {};
      val.list.forEach((v) => {
        // 确保v.id存在
        if (v.id) {
          if (this.skuTableObj[v.id]) {
            objValue[v.id] = this.skuTableObj[v.id]; // 直接继承已有的规格值ID
          } else {
            objValue[v.id] = []; // 初始化为空数组，用于存储选中的规格值ID
          }
        }
        // 保存规格项信息
      });
      this.skuTableObj = { ...objValue };
      this.skuTableList = [...val.list];
      // 初始化完成后生成商品
      this.$nextTick(() => {
        this.generateProducts();
      });
    },

    deleteSkuTable(index, id) {
      // 确保id存在且在skuTableObj中
      if (id && this.skuTableObj.hasOwnProperty(id)) {
        this.skuTableObj[id] = [];
      }
      // 确保index有效再删除
      if (index >= 0 && index < this.skuTableList.length) {
        this.skuTableList.splice(index, 1);
      }
      this.generateProducts();
    },

    // 根据选中的规格生成商品
    generateProducts() {
      // console.log("生成商品列表，当前选中规格:", this.skuTableObj);

      // 获取所有选中的规格项
      const selectedSpecs = [];
      for (const key in this.skuTableObj) {
        const spec = this.skuTableList.find((item) => item.id == key);
        if (spec && this.skuTableObj[key].length > 0) {
          // 获取选中的规格值详情
          const selectedValues = spec.childrenList.filter((child) =>
            this.skuTableObj[key].includes(child.id)
          );
          selectedSpecs.push({
            id: spec.id,
            name: spec.name,
            values: selectedValues,
          });
        }
      }

      // 如果没有选中的规格，则清空商品列表
      if (selectedSpecs.length === 0) {
        this.form.productSkuSetList = [];
        return;
      }

      // 生成笛卡尔积组合
      const combinations = this.cartesianProduct(selectedSpecs);

      // 保存当前已有的商品数据，用于继承
      const existingProducts = [...this.form.productSkuSetList];

      // 根据组合生成商品列表
      this.form.productSkuSetList = combinations.map((combo, index) => {
        // 按照规格项在skuTableList中的顺序排列规格值
        const orderedCombo = [];
        this.skuTableList.forEach((specItem) => {
          const found = combo.find((item) => item.spec.id === specItem.id);
          if (found) {
            orderedCombo.push(found);
          }
        });

        // 构造规格名称（按规格项顺序排列）
        const skuSetName = orderedCombo
          .map((item) => item.value.name)
          .join(",");

        // 构造唯一ID（由选中规格值的ID用下划线拼接，并按ID从小到大排序，前后各加一个下划线）
        const ids = orderedCombo
          .map((item) => item.value.id)
          .sort((a, b) => a - b);
        const skuHashCode = "_" + ids.join("_") + "_";

        // 构造规格数据数组（按规格项顺序排列）
        const skuSetValue = orderedCombo.map((item) => ({
          id: item.value.id,
          name: item.value.name,
        }));

        // 查找是否已存在该组合的商品数据
        let existingProduct = null;
        // 先精确匹配ID
        existingProduct = existingProducts.find(
          (product) => product.skuHashCode === skuHashCode
        );

        // 如果没有精确匹配，尝试通过规格名称匹配（用于兼容旧数据）
        if (!existingProduct) {
          const names = orderedCombo.map((item) => item.value.name).sort();
          const nameKey = names.join(",");
          existingProduct = existingProducts.find(
            (product) => product.skuSetName === nameKey
          );
        }

        // 返回商品对象，如果有已存在的数据则继承，否则使用默认值
        return {
          skuHashCode: skuHashCode,
          skuSetName: skuSetName,
          skuSetValue: skuSetValue,
          cover: existingProduct ? existingProduct.cover : "",
          code: existingProduct ? existingProduct.code : "",
          marketPrice: existingProduct
            ? existingProduct.marketPrice
            : undefined,
          salePrice: existingProduct ? existingProduct.salePrice : undefined,
          exchangePoint: existingProduct
            ? existingProduct.exchangePoint
            : undefined,
          weight: existingProduct ? existingProduct.weight : undefined,
          volume: existingProduct ? existingProduct.volume : undefined,
          stock: existingProduct ? existingProduct.stock : undefined,
          costPrice: existingProduct ? existingProduct.costPrice : undefined,
        };
      });
      // console.log("最终商品列表:", this.form.productSkuSetList);

      // 触发表单验证以更新验证状态
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      });
    },

    // 计算笛卡尔积
    cartesianProduct(specs) {
      // 按照skuTableList中的顺序重新排列specs
      const orderedSpecs = [];
      this.skuTableList.forEach((specItem) => {
        const found = specs.find((spec) => spec.id === specItem.id);
        if (found) {
          orderedSpecs.push(found);
        }
      });

      if (orderedSpecs.length === 0) return [];

      return orderedSpecs.reduce((acc, spec) => {
        const newAcc = [];
        if (acc.length === 0) {
          // 第一个规格，直接返回其所有值
          spec.values.forEach((value) => {
            newAcc.push([{ spec: spec, value: value }]);
          });
        } else {
          // 与其他规格进行组合
          acc.forEach((combination) => {
            spec.values.forEach((value) => {
              newAcc.push([...combination, { spec: spec, value: value }]);
            });
          });
        }
        return newAcc;
      }, []);
    },

    // 获取当前的商品SKU数据
    getProductSkuData() {
      return this.form.productSkuSetList;
    },

    // 设置商品SKU数据（用于数据继承）
    setProductSkuData(data) {
      this.form.productSkuSetList = data;
      // 重新生成商品列表以确保数据一致性
      this.generateProducts();
    },
    // 设置规格项数据
    setSkuTableList(skuTableData) {
      this.$nextTick(() => {
        if (skuTableData && Array.isArray(skuTableData)) {
          // 构造skuTableObj对象
          const skuTableObj = {};
          const skuTableList = [];

          skuTableData.forEach((item) => {
            if (item.head && item.values) {
              // 初始化规格项的选中值ID数组
              skuTableObj[item.head.id] = item.values.map((value) => value.id);
            }
          });

          this.skusTreeList.forEach((item) => {
            if (skuTableObj[item.id]) {
              skuTableList.push(item);
            }
          });
          this.skuTableObj = skuTableObj;
          this.skuTableList = skuTableList;
        }
      });
    },
    // 编辑时数据回显方法
    setEditData(skuTableData, productSkuSetList) {
      // console.log("设置编辑数据", skuTableData, productSkuSetList);
      // console.log("skuTableData", skuTableData);
      // console.log("productSkuSetList", productSkuSetList);
      // 设置规格项数据
      if (this.skusTreeList.length) {
        this.setSkuTableList(skuTableData);
      } else {
        this.getSkusTree(skuTableData);
      }

      // 设置商品SKU数据
      if (productSkuSetList && Array.isArray(productSkuSetList)) {
        this.form.productSkuSetList = JSON.parse(
          JSON.stringify(productSkuSetList)
        );
      }
    },
    // 验证表单
    validate() {
      return new Promise((resolve) => {
        this.$refs.form.validate((valid) => {
          // console.log("表单验证结果", valid);
          // console.log("productSkuSetList", this.form.productSkuSetList);
          // console.log("skuTableObj", this.skuTableObj);
          // 如果表单验证通过，再验证商品SKU列表
          if (valid) {
            // 检查是否有商品SKU数据
            if (
              this.form.productSkuSetList &&
              this.form.productSkuSetList.length > 0
            ) {
              // 验证每个商品SKU的必填字段
              // 处理规格数据
              let skuTable = [];
              this.skuTableList.forEach((v) => {
                let obj = {};
                if (
                  this.skuTableObj[v.id] &&
                  this.skuTableObj[v.id].length > 0 &&
                  v.childrenList
                ) {
                  obj.head = {
                    id: v.id,
                    name: v.name,
                  };
                  obj.values = [];
                  v.childrenList.forEach((j) => {
                    if (this.skuTableObj[v.id].includes(j.id)) {
                      obj.values.push({
                        id: j.id,
                        name: j.name,
                      });
                    }
                  });
                }
                if (obj.head) {
                  skuTable.push(obj);
                }
              });
              // console.log("skuTable", skuTable);
              resolve({
                valid,
                value: valid
                  ? {
                      productSkuSetList: this.form.productSkuSetList,
                      skuTable,
                    }
                  : null,
                message: valid ? "" : "请完善所有商品规格信息",
              });
            } else {
              resolve({
                valid: false,
                value: null,
                message: "请至少选择一个商品规格",
              });
            }
          } else {
            resolve({
              valid: false,
              value: null,
              message: "请完善表单信息",
            });
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
}
.m-10 {
  margin: 0 10px 5px 10px;
}
.box-card {
  margin-bottom: 10px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>
