<template>
  <view class="skuEdit">
    <wd-table rowHeight="100" :data="Pdata.use_sku == 0
      ? skuDefault
      : skuLibrary
      " :stripe="false">
      <wd-table-col prop="name" label="SKU">

        <template #value="scope">
          <view class="custom-class">
            <span style="margin-right: 4px" v-for="(item, index) of scope.row
              .attr_list" :key="index">
              {{ item.name }}
            </span>
          </view>
        </template>

      </wd-table-col>
      <wd-table-col prop="school" label="售价">
        <template #value="scope">
          <view class="px-2 pb-1 bg-white">
            <wd-input placeholder="售价" v-model="scope.row.price" type="number" />
          </view>
        </template>
      </wd-table-col>
      <wd-table-col prop="major" label="原价">
        <template #value="scope">
          <view class="px-2 pb-1 bg-white">
            <wd-input placeholder="原价" v-model="scope.row.original_price" type="number">
            </wd-input>
          </view>
        </template>
      </wd-table-col>
      <wd-table-col prop="major" label="库存">
        <template #value="scope">
          <view class="px-2 pb-1 bg-white">
            <wd-input placeholder="库存" v-model="scope.row.stock" type="number">
            </wd-input>
          </view>
        </template>
      </wd-table-col>
      <wd-table-col prop="major" label="产品号">
        <template #value="scope">
          <view class="px-2 pb-1 bg-white">
            <wd-input placeholder="产品号" v-model="scope.row.no">
            </wd-input>
          </view>
        </template>
      </wd-table-col>

      <wd-table-col prop="major" label="产品图">
        <template #value="scope">
          <view class="overflow-hidden w-full h-full flex items-center justify-center">
            <view class="px-2 pb-1 bg-white flex items-center justify-center mt-4 overflow-hidden">
              <myUpload v-model="scope.row.pic_url"></myUpload>
            </view>
          </view>
        </template>
      </wd-table-col>

    </wd-table>

    <view v-show="Pdata.use_sku == 1" class="bg-gray-100  rounded mb-2">
      <div class="p-2 bg-white w-full">
        <div class="name mb-2 text-xs">规格设置</div>
        <view class="flex bg-white px-3 py-1 rounded w-full">
          <div class="flex-1 mr-4">
            <wd-input type="text" v-model="addGroupData.name" />
          </div>
          <wd-button @click="addSkuGroup">添加规格组</wd-button>
        </view>
      </div>

      <div class="p-2 bg-white">
        <div style="display: flex; flex-flow: column; align-items: flex-start;">
          <div class="name mb-2 text-xs">规格组</div>

          <div class="w-full bg-gray-100 p-2" v-for="(item, index) in skuGroup" :key="index">
            <div class="flex items-center justify-between w-full bg-white p-2">
              <div class="mr-3">
                <wd-tag type="primary" custom-class="space" closable @close="moveGroup(index)">{{
                  item.name }}</wd-tag>
              </div>
              <div class="mr-3">
                <wd-input type="text" v-model="addGouppItemData[index]" />
              </div>
              <wd-button type="warning" @click="addGroupItem(index)">添加规格</wd-button>
            </div>
            <div type="flex" style="margin: 12px 0;">
              <div class="name mb-2 text-xs">规格:</div>
              <view class="flex gap-2 flex-wrap">
                <wd-tag custom-class="space1" closable round type="warning" class="mx-1"
                  v-for="(value, key) in item.groupItem" :key="key" style="margin-left: 10px"
                  @close="removeGroupItem(index, key)">{{ value.name
                  }}</wd-tag>
              </view>
            </div>
          </div>
        </div>
      </div>

    </view>


  </view>
</template>

<script>
import myUpload from "@/components/myUpload/index.vue"
import { useToast } from '@/uni_modules/wot-design-uni'
const toast = useToast()

export default {
  name: "skuEdit",
  props: {
    Pdata: {
      type: Object,
      default: () => ({})
    },
  },
  components: {
    myUpload
  },
  data() {
    return {
      // sku规格开始
      skuDefault: [
        {
          attr_list: [{ group_name: "默认", name: "默认" }],
          price: "", // 售价
          original_price: "", // 原价
          stock: "", // 库存
          pic_url: "", // 图片
          no: "", // 货号
        },
      ],
      skuGroup: [],
      addGroupData: {
        name: "",
        groupItem: [],
      }, //添加规格组默认数据
      addGouppItemData: [],
      skuLibrary: [], // 规格库
      // 批量设置
      all_price: "",
      all_original_price: "",
      all_stock: "",
      all_no: "",
      // sku规格结束
    }
  },
  created() {
    this.skuDefault = this.Pdata.skuDefault.length ? this.Pdata.skuDefault : this.skuDefault
    this.skuLibrary = this.Pdata.skuLibrary
    this.skuGroup = this.Pdata.skuGroup
  },
  methods: {
    successImage($event, index) {
      console.log($event, index);
    },

    /**
* 处理规格数据
*/
    setGoodsAttrItem(attrGroup, attrList, index) {
      var attrList1 = [];
      if (index < attrGroup.length) {
        if (index === 0 || attrList.length === 0) {
          if (attrGroup[index].groupItem.length > 0) {
            attrGroup[index].groupItem.forEach((element) => {
              element.group_name = attrGroup[index].name;
              attrList1.push([element]);
            });
          }
        } else {
          if (attrGroup[index].groupItem.length > 0) {
            attrList.forEach((element) => {
              attrGroup[index].groupItem.forEach((element1) => {
                element1.group_name = attrGroup[index].name;
                attrList1.push(element.concat([element1]));
              });
            });
          } else {
            attrList1 = attrList;
          }
        }
        ++index;
        return this.setGoodsAttrItem(attrGroup, attrList1, index);
      } else {
        return attrList;
      }
    },

    /**
     * 获取其他详细数据
     */
    getAttrDataInfo(attr) {
      var attrList = [];
      attr.forEach((element) => {
        var setAttr = {};
        if (this.skuLibrary) {
          this.skuLibrary.forEach((element2) => {
            if (element2.attr_list.length === element.length) {
              var loading = true;
              if (
                loading &&
                this.compareAttr(element2.attr_list, element)
              ) {
                setAttr = element2;
                loading = false;
              }
            }
          });
        }

        var data = {
          id: setAttr && setAttr.id ? setAttr.id : 0,
          attr_list: element,
          price: setAttr && setAttr.price ? setAttr.price : element.reduce((price, i) => price + i.price, 0).toFixed(2),
          original_price:
            setAttr && setAttr.original_price
              ? setAttr.original_price
              : element.reduce((price, i) => price + i.price, 0).toFixed(2),
          stock: setAttr && setAttr.stock ? setAttr.stock : 0,
          pic_url: setAttr && setAttr.pic_url ? setAttr.pic_url : "",
          no: setAttr && setAttr.no ? setAttr.no : "",
        };
        for (const key in setAttr) {
          if (key.indexOf("member") !== -1) {
            data[key] = setAttr[key];
          }
        }
        attrList.push(data);
      });
      return attrList;
    },
    compareAttr(val1, val2) {
      var compareLen = 0;
      val1.forEach((element1) => {
        val2.forEach((element2) => {
          if (element1.name === element2.name) {
            compareLen++;
          }
        });
      });
      return compareLen === val1.length;
    },
    // 添加规格组
    addSkuGroup() {

      if (!this.addGroupData.name) {
        uni.showToast({
          title: '请填写规格组名称',
          icon: 'none'
        })
        return
      }

      // 添加一个一个规格类
      console.log("添加了一个规格组");
      this.skuGroup.push(this.addGroupData);
      console.log("skuGroup发生了变换");
      // 回复默认数据
      this.addGroupData = {
        name: "",
        groupItem: [],
      };
    },

    // 删除规格组
    moveGroup(index) {
      if (this.skuGroup[index].groupItem.length === 0) {
        console.log("删除的组合没有规格！！！");
        this.skuGroup.splice(index, 1);

        return
      }

      this.skuGroup.splice(index, 1);
      var attrList = this.setGoodsAttrItem(this.skuGroup, [], 0);
      this.skuLibrary = this.getAttrDataInfo(attrList);
      this.calculateCombinationPrice(this.skuLibrary);
    },
    // 计算组合价格的方法
    calculateCombinationPrice(skuLibrary) {
      console.log(skuLibrary);
      skuLibrary.forEach((sku) => {
        // 计算每个 SKU 组合的价格
        let combinationPrice = 0;

        // 遍历 SKU 的属性列表
        sku.attr_list.forEach((attr) => {
          // 累加每个属性项的价格
          combinationPrice += attr.price;
        });

        // 将组合价格保存到 SKU 对象中
        sku.price = combinationPrice.toFixed(2);
        sku.original_price = combinationPrice.toFixed(2);
      });

      this.skuLibrary = skuLibrary

    },
    // 添加规格
    addGroupItem(index) {
      const _skuGroup = this.skuGroup

      if (this.skuGroup[index].groupItem.length === 0) {
        console.log("新的组合出现了！！！");
        // 计算组合价格
        setTimeout(() => {
          // console.log(this.skuGroup);
          this.calculateCombinationPrice(this.skuLibrary);
        });
      } else {
        console.log(_skuGroup);
      }


      if (!this.addGouppItemData[index]) {
        if (!this.addGroupData.name) {
          uni.showToast({
            title: '请填写规格名称',
            icon: 'none'
          })
          return
        }

        return
      }

      this.skuGroup[index].groupItem.push({
        group_name: this.skuGroup[index].name,
        name: this.addGouppItemData[index],
        price: 0
      });
      console.log(this.skuGroup);

      // todo 这里还有问题
      var attrList = this.setGoodsAttrItem(this.skuGroup, [], 0);
      console.log(attrList);
      this.skuLibrary = this.getAttrDataInfo(attrList);
      this.addGouppItemData = [];

      // // 计算组合价格
      // this.calculateCombinationPrice(this.skuLibrary);
    },

    // 删除规格
    removeGroupItem(index, key) {
      this.skuGroup[index].groupItem.splice(key, 1);
      var attrList = this.setGoodsAttrItem(this.skuGroup, [], 0);
      this.skuLibrary = this.getAttrDataInfo(attrList);
    },
  }
}
</script>

<style lang="scss" scoped>
:deep(.space) {
  padding: 6px 10px;
}

:deep(.space1) {
  padding: 6px 10px;
  background: #f0883a !important;
  color: white !important;

  .wd-tag__close {
    color: white;
  }
}
</style>
