<template>
  <el-form-item :label-width="labelWidth" label="商品规格">
    <div style="display: block;width: 100%;">
      <!-- <el-input-number v-model.number="formData.goodsSpec" controls-position="right" :min="0.01"
                    :precision="2" /> -->
      <el-alert v-if="isAdd" title="注意：上架商品后无法修改规格！请谨慎填写" type="warning " show-icon :closable="false" />
      <div class="input-intro">最多添加3个商品规格组，生成的SKU数量不能超出50个</div>

      <!-- 规格样式 -->
      <div class="sepc-big-box" v-for="(item, index) in goodsSpecList">
        <div class="sepc-title-box">
          <el-input v-model="item.specName" @change="handleChangeSepc(item, index)" class="spec-input" placeholder="规格组名称"
            :clearable="isAdd" :disabled="!isAdd" />
          <el-link type="primary" @click="handleDelSpec(item)" v-if="isAdd">删除规格组</el-link>
        </div>
        <div class="spec-value-box">
          <div class="spec-value-input-big-box">
            <div class="spec-value-input-box" v-for="specValue in item.props">
              <div v-if="isAdd" class="spec-value-input-del" @click="handleDelSpecValue(item, specValue)"><el-icon>
                  <Close />
                </el-icon></div>
              <el-input v-model="specValue.specValueName" @change="handleChangeSepcValue()" class="spec-value-input"
                placeholder="规格值名称" :disabled="!isAdd" :clearable="isAdd" />
            </div>
          </div>
          <el-link type="primary" v-if="isAddSpecValueMax && isAdd" @click="handleAddSpecValue(item)">添加规格值</el-link>
        </div>
      </div>

      <el-button v-if="isAddSpecMax && isAdd" class="mt-5" @click="handleAddSpec">
        <el-icon class="avatar-uploader-icon">
          <plus />
        </el-icon>
        添加规格组
      </el-button>
    </div>
  </el-form-item>


  <!-- Sku列表 -->
  <el-form-item :label-width="labelWidth" label="Sku列表">

    <!-- sku列表 -->

    <el-table :data="skuList" border style="width: 100%" :span-method="objectSpanMethod">
      <!-- 动态列 -->
      <el-table-column v-for="column in skuColumns" :prop="column.prop" :label="column.label" :key="column.key"
        :width="column.width">
      </el-table-column>

      <el-table-column prop="goodsSkuImg" label="预览图" width="125" align="center">
        <template #default="scope">
          <UploadImage ref="uploadRef" :disabled="!isAdd" v-model="scope.row.goodsSkuImg" :data=imgData :limit="1" :fileSize="5" :drag="true"
            :isShowTip="false" />
        </template>
      </el-table-column>

      <el-table-column prop="goodsSkuPrice" label="商品价格" width="145">
        <template #default="scope">
          <el-input-number v-model.number="scope.row.goodsSkuPrice" controls-position="right" :min="0" :precision="2" :disabled="!isAdd" />
        </template>
      </el-table-column>

      <el-table-column prop="goodsSkuLinePrice" label="划线价格" width="145">
        <template #default="scope">
          <el-input-number v-model.number="scope.row.goodsSkuLinePrice" controls-position="right" :min="0"
            :precision="2" :disabled="!isAdd" />
        </template>
      </el-table-column>

      <el-table-column prop="goodsSkuStockNum" label="库存数量" width="145">
        <template #default="scope">
          <el-input-number v-model.number="scope.row.goodsSkuStockNum" controls-position="right" :min="0" :disabled="!isAdd"/>
        </template>
      </el-table-column>

      <el-table-column prop="goodsSkuWeight" label="商品重量 (KG)" width="145">
        <template #default="scope">
          <el-input-number v-model.number="scope.row.goodsSkuWeight" controls-position="right" :min="0" :precision="2" :disabled="!isAdd"/>
        </template>
      </el-table-column>

      <el-table-column prop="goodsSkuSkuCode" label="SKU编码" width="145">
        <template #default="scope">
          <el-input v-model="scope.row.goodsSkuSkuCode" placeholder="" :disabled="!isAdd"/>
        </template>
      </el-table-column>

    </el-table>

  </el-form-item>
</template>

<script setup>
import descartes from "./dikaerji";

const props = defineProps({
  modelValue: Object,
  isAdd: Boolean,
});

watch(props, async (v) => {
  goodsSpecList.value = v.modelValue.goodsSpecList;
  if (v.modelValue.goodsSpecList && v.modelValue.goodsSpecList.length !== 0) {
    skuColumns.value = []; // 清空原有的表头

    // 遍历规格组列表
    v.modelValue.goodsSpecList.forEach((specGroup, index) => {
      let prop;
      if (index === 0) {
        prop = 'specValue';
      } else if (index === 1) {
        prop = 'specSecondValue';
      } else if (index === 2) {
        prop = 'specThirdValue';
      }

      const column = {
        prop: prop, // 使用属性名称
        label: specGroup.specName, // 使用规格组的名称作为标签
        width: '100'
      };

      skuColumns.value.push(column); // 将表头对象添加到skuColumns数组
    });
  }
  console.log(v.modelValue.skuList, '原数据');
  skuList.value = v.modelValue.skuList;
  if (v.modelValue.skuList && v.modelValue.skuList.length !== 0) {
    getSpanArr(skuList.value);
  }
});


/** 商品规格 业务参数 */

// 添加商品规格按钮状态
const isAddSpecMax = ref(true)
const isAddSpecValueMax = ref(true)

// 动态表头
const skuColumns = ref([
  // {
  //   prop: 'specValue',
  //   label: '颜色',
  //   width: '100'
  // },
  // {
  //   prop: 'specSecondValue',
  //   label: '内存',
  //   width: '100'
  // },
  // {
  //   prop: 'specThirdValue',
  //   label: '版本',
  //   width: '100'
  // },
])

// 规格组
const goodsSpecList = ref([
  // 规格值Json属性
  // {
  //   specId: 0,
  //   specName: "",
  //   props: [
  //     {
  //       specValueId: 0,
  //       specValueName: "",
  //       specValue: "",
  //     },
  //   ],
  // },
  // {
  //   specId: 0,
  //   specName: "",
  //   props: [
  //     {
  //       specValueId: 0,
  //       specValueName: "",
  //       specValue: "",
  //     },
  //   ],
  // },
])

// sku列表
const skuList = ref([
])

/** sku列表参数 */
const newList = ref([])
const newData = ref([])
const spanArr = ref([])
const spanArr1 = ref([])
const pos = ref("")
const pos1 = ref("")
const imgData = ref({
  fileDir: "Goods"
})


/** sku列表方法 */


//处理数据（拆分规格组里的规格值为数组）
const processing = () => {
  newData.value = [];
  goodsSpecList.value.forEach((item) => {
    const prop = item.props.map((prop) => prop.specValueName);
    newData.value.push(prop);
  });
  console.log(newData.value, '各规格组中的规格值');
  getList();
}


//转换数据
const getList = () => {
  skuList.value = [];
  newList.value = descartes(newData.value);
  console.log(newList.value, '笛卡尔积处理过后的数据');
  newList.value.forEach((item) => {
    skuList.value.push({
      specValue: Array.isArray(item) ? item[0] : item,
      specSecondValue: Array.isArray(item) ? item[1] : null,
      specThirdValue: Array.isArray(item) ? item[2] : null,
      goodsGuid: 0,
      goodsSkuId: 0,
      goodsSkuImg: "",
      goodsSkuPrice: 0.01,
      goodsSkuLinePrice: 0,
      goodsSkuStockNum: 0,
      goodsSkuWeight: 0,
      goodsSkuSkuCode: "",
    });
  });

  props.modelValue.goodsSpecList = goodsSpecList.value
  props.modelValue.skuList = skuList.value

  getSpanArr(skuList.value);
  console.log(skuList.value, '表格中的数据');
}

// 合并已存在的sku数据
// function oldSkuList(newSkuList) {
//   // const oldSkuList = _.cloneDeep(this.multiSpecData.skuList)
//   const oldSkuList = skuList.value.concat()
//   if (!oldSkuList.length || !newSkuList.length) {
//     return newSkuList
//   }
//   for (const index in newSkuList) {
//     // 查找符合的旧记录
//     let oldSkuItem = {}
//     if (oldSkuList.length === newSkuList.length) {
//       oldSkuItem = _.cloneDeep(oldSkuList[index])
//     } else {
//       oldSkuItem = oldSkuList.find(item => {
//         return item.key === newSkuList[index].key
//       })
//     }
//     // 写入新纪录
//     if (oldSkuItem) {
//       newSkuList[index] = {
//         ...newSkuList[index],
//         ..._.pick(oldSkuItem, Object.keys({
//           goodsGuid: 0,
//           goodsSkuImg: "",
//           goodsSkuPrice: 0.01,
//           goodsSkuLinePrice: 0,
//           goodsSkuStockNum: 0,
//           goodsSkuWeight: 0,
//           goodsSkuSkuCode: "",
//         }))
//       }
//       // console.log(newSkuList[index].image)
//     }
//   }
//   return newSkuList
// }


//计算位置的方法
const getSpanArr = (data) => {
  spanArr.value = [];
  pos.value = "";
  spanArr1.value = [];
  pos1.value = "";
  data.forEach((item, i) => {
    if (i === 0) {
      spanArr.value.push(1);
      pos.value = 0;
    } else {
      if (item.specValue === data[i - 1].specValue) {
        spanArr.value[pos.value] += 1;
        spanArr.value.push(0);
      } else {
        spanArr.value.push(1);
        pos.value = i;
      }
    }
  });


  data.forEach((item, i) => {
    if (item.specThirdValue != null) {
      if (i === 0) {
        spanArr1.value.push(1);
        pos1.value = 0;
      } else {
        if (item.specSecondValue === data[i - 1].specSecondValue) {
          spanArr1.value[pos1.value] += 1;
          spanArr1.value.push(0);
        } else {
          spanArr1.value.push(1);
          pos1.value = i;
        }
      }
    }
  });
  console.log(spanArr.value, '排序Arr');
  console.log(spanArr1.value, '排序Arr1');
}


// 合并行数
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // columnIndex === 0 找到第一列，实现合并随机出现的行数
  if (goodsSpecList.value && goodsSpecList.value.length !== 0) {
    if (columnIndex === 0) {
      const _row = spanArr.value[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return {
        rowspan: _row,
        colspan: _col
      };
      // columnIndex === 1 找到第二列，合并他的列数
    } else if (columnIndex === 1) {
      if (spanArr1.value.length != 0) {
        const _row = spanArr1.value[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    }
  }
}



/** 商品规格 业务方法 */

// 添加规格组
function handleAddSpec() {
  let data = {
    specId: 0,
    specName: "",
    key: 0,
    props: [

    ]
  }
  goodsSpecList.value.push(data)

  if (goodsSpecList.value.length == 3) {
    isAddSpecMax.value = false
  }
}

// 修改规格组
function handleChangeSepc(item, idx) {

  item.key = idx
  let foundMatch = false;
  skuColumns.value.map((i, index) => {
    if (i.key == idx) {
      i.label = item.specName
      foundMatch = true
      return true
    }
  })

  if (foundMatch) {
    return; // 停止执行后续代码
  }

  let propValue = ""
  if (idx === 0) {
    propValue = "specValue"
  }
  if (idx === 1) {
    propValue = "specSecondValue"
  }
  if (idx === 2) {
    propValue = "specThirdValue"
  }

  // 添加动态表头
  let column = {
    prop: propValue,
    label: item.specName,
    width: '100',
    key: idx
  }
  skuColumns.value.push(column)
}

// 删除规格组
function handleDelSpec(item) {
  const index = goodsSpecList.value.indexOf(item);
  if (index > -1) {
    goodsSpecList.value.splice(index, 1);
    processing()
  }

  if (goodsSpecList.value.length < 3) {
    isAddSpecMax.value = true
  }


  // 删除对应的表头
  skuColumns.value = skuColumns.value.filter(column => column.label !== item.specName);

  // 删除对应的sku
  // skuColumns.value = skuColumns.value.filter(column => column.specName !== item.specName);


}




// 添加规格值
function handleAddSpecValue(item) {
  let data = {
    specId: 0,
    specValueId: 0,
    specValueName: "",
  }
  item.props.push(data)

  if (item.props.length == 50) {
    isAddSpecValueMax.value = false
  }
}


// 修改规格值
function handleChangeSepcValue(e) {

  // 添加sku
  processing()
}


// 删除规格值
function handleDelSpecValue(item, specValue) {
  const index = item.props.indexOf(specValue);
  if (index > -1) {
    item.props.splice(index, 1);
    processing()
  }

  if (item.props.length < 50) {
    isAddSpecValueMax.value = true
  }
}


</script>


<style lang="scss" scoped>
.divider-title {
  font-size: 18px;
}

.input-intro {
  color: #8c8c8c;
  font-size: 12px;
}

.el-divider {
  margin: 50px 0;
}

.sepc-big-box {
  width: 100%;
  margin-bottom: 20px;
}

.sepc-title-box {
  width: 100%;
  padding: 10px;
  background-color: #f4f4f5;
  display: flex;
  justify-content: space-between;
}

.spec-value-box {
  width: 100%;
  padding: 20px 20px 20px 40px;
  background-color: #fbfbfb;
  display: flex;
  flex-wrap: wrap;
}

.spec-value-input-big-box {
  display: flex;
  flex-wrap: wrap;
}

.spec-value-input-box {
  width: 250px;
  position: relative;
  margin-right: 30px;
  margin-bottom: 15px;
}

.spec-value-input-del {
  position: absolute;
  top: -5px;
  right: -5px;
  z-index: 99;
  width: 18px;
  height: 18px;
  background-color: grey;
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 10px;
  cursor: pointer;
}

.spec-input {
  width: 250px;
  margin-right: 30px;
}


.mt-5 {
  margin-top: 10px;
}

.el-input-number {
  width: 120px;
}

:deep(.el-upload--picture-card) {
  width: 90px;
  height: 90px;
}

:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 100px;
}
</style>
