<template>
    <div class="sku-list">
      <template v-if="!disabled">
        <div class="sku-list-head">
          <el-button type="primary" size="mini" @click="addSkuRow">添加规格</el-button>
        </div>
        <div
          class="sku-list-item"
          v-for="(item, index) in skuData.attrList"
          :key="index"
        >
          <div class="sku-list-item-main">
            <div class="sku-list-item__layout">
              <span class="span">规格名称</span>
              <el-input
                size="small"
                v-model="item.name"
                class="input"
              ></el-input>
            </div>
            <div class="sku-list-item__layout">
              <span class="span">规格值</span>
              <div class="sku-list-item-tags">
                <el-tag
                  class="sku-list-item-tag"
                  closable
                  v-for="(subItem, i) in item.child"
                  v-if="subItem.name"
                  @close="removeSkuAttr(index, i)"
                  :key="i"
                >{{ subItem.name }}</el-tag>
                <el-button
                  size="small"
                  icon="el-icon-plus"
                  @click="addSkuAttr(index)"
                >添加</el-button>
              </div>
            </div>
          </div>
          <el-button
            type="text"
            size="small"
            class="sku-list-item-removeBtn"
            @click="removeSkuRow(index)"
          >删除规格</el-button>
        </div>
      </template>
  
      <div class="batch-setting">
        <span class="label">批量设置</span>
        <el-input size="small" v-model="batch.skuNo" placeholder="SKU 编号" class="input input-sn"></el-input>
        <span class="create-sn" @click="createGoodsSn()">随机生成</span>
        <el-input size="small" v-model="batch.price" placeholder="商品价格" class="input"></el-input>
        <el-input size="small" v-model="batch.linePrice" placeholder="原价" class="input"></el-input>
        <el-input size="small" v-model="batch.stock" placeholder="商品库存" class="input"></el-input>
        <el-input size="small" v-model="batch.weight" placeholder="重量" class="input"></el-input>
        <el-button size="small" type="danger" class="button" @click="batchSetSku()">确认设置</el-button>
      </div>
  
      <el-table border :data="skuData.skuList">
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" width="120">
          <template #default="scope">
            <el-upload
              :disabled="disabled"
              :action="uploadAction"
              list-type="picture-card"
              :auto-upload="true"
              :headers="uploadHeader"
              :file-list="[]"
              :limit="1"
              :on-success="(file) => onUploadImgSuccess(file, scope.$index)"
              :show-file-list="false"
            >
              <img
                v-if="scope.row.logo"
                :src="uploadDomain + scope.row.logo"
                class="sku-logo"
              />
              <i v-if="!scope.row.logo" class="el-icon-plus"></i>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="规格" align="center">
          <template #default="scope">
            <div class="spec-tag" v-for="spec in scope.row.specList">
              <span class="i">{{ spec.value }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="SKU 编码" align="center" width="160">
          <template #default="scope">
            <el-input
              :readonly="disabled"
              v-model="scope.row.skuNo"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="销售价格" align="center">
          <template #default="scope">
            <el-input
              :readonly="disabled"
              v-model="scope.row.price"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="原价" align="center">
          <template #default="scope">
            <el-input
              :readonly="disabled"
              v-model="scope.row.linePrice"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center">
          <template #default="scope">
            <el-input :readonly="disabled" v-model="scope.row.stock"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="重量" align="center">
          <template #default="scope">
            <el-input :readonly="disabled" v-model="scope.row.weight"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, defineProps, defineEmits } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  
  // 模拟获取 token
  const getToken = () => 'mockedToken';
  
  // 定义 props
  const props = defineProps({
    goodsId: {
      type: String,
      default: ""
    },
    uploadDomain: {
      type: String,
      default: ""
    },
    skuData: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    }
  });
  
  // 定义 emits
  const emits = defineEmits(['skuChange']);
  
  // 上传地址
  const uploadAction = ref('/backendApi/file/upload');
  const uploadHeader = ref({ 'Access-Token': getToken() });
  
  // 批量设置
  const batch = ref({ price: '', skuNo: '', linePrice: '', weight: '', stock: '' });
  
  // 监听 skuData.attrList 变化
  watch(() => props.skuData.attrList, () => {
    if (!props.disabled) {
      const newSkuList = getTable();
      props.skuData.skuList = newSkuList;
      emits('skuChange', props.skuData);
    }
  }, { deep: true, immediate: true });
  
  // 添加规格行
  const addSkuRow = () => {
    ElMessageBox.prompt('请输入规格名称', '添加规格', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '规格名称不能为空',
      closeOnClickModal: false
    }).then(({ value }) => {
      // 模拟接口请求
      const mockResponse = { data: { id: 1 } };
      props.skuData.attrList.push({
        id: mockResponse.data.id,
        name: value,
        child: []
      });
      emits('skuChange', props.skuData);
    }).catch(() => {});
  };
  
  // 删除规格行
  const removeSkuRow = (i) => {
    ElMessageBox.confirm('确认删除该规格行吗？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 模拟接口请求
      const mockResponse = { data: {} };
      props.skuData.attrList.splice(i, 1);
      emits('skuChange', props.skuData);
    }).catch(() => {});
  };
  
  // 删除规格属性值
  const removeSkuAttr = (a, b) => {
    ElMessageBox.confirm('确认删除该规格属性值吗？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 模拟接口请求
      const mockResponse = { data: {} };
      props.skuData.attrList[a].child.splice(b, 1);
      emits('skuChange', props.skuData);
    }).catch(() => {});
  };
  
  // 添加规格属性值
  const addSkuAttr = (i) => {
    ElMessageBox.prompt('请输入规格属性值', '添加规格属性值', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '规格属性值不能为空',
      closeOnClickModal: false
    }).then(({ value }) => {
      // 模拟接口请求
      const mockResponse = { data: { id: 1 } };
      props.skuData.attrList[i].child.push({
        id: mockResponse.data.id,
        name: value,
        value: value
      });
      emits('skuChange', props.skuData);
    }).catch(() => {});
  };
  
  // 批量设置 sku
  const batchSetSku = () => {
    props.skuData.skuList.forEach((skuInfo, index) => {
      if (batch.value.skuNo) {
        skuInfo.skuNo = batch.value.skuNo + index;
      }
      if (batch.value.price) {
        if (batch.value.price > 0) {
          skuInfo.price = batch.value.price;
        } else {
          ElMessage.error('价格必须大于零');
          return;
        }
      }
      if (batch.value.linePrice) {
        if (batch.value.linePrice >= 0) {
          skuInfo.linePrice = batch.value.linePrice;
        } else {
          ElMessage.error('原价必须大于等于零');
          return;
        }
      }
      if (batch.value.weight) {
        if (batch.value.weight >= 0) {
          skuInfo.weight = batch.value.weight;
        } else {
          ElMessage.error('重量必须大于等于零');
          return;
        }
      }
      if (batch.value.stock) {
        if (batch.value.stock >= 0) {
          skuInfo.stock = batch.value.stock;
        } else {
          ElMessage.error('库存必须大于等于零');
          return;
        }
      }
    });
    emits('skuChange', props.skuData);
  };
  
  // 生成随机条码
  const createGoodsSn = () => {
    let sn = (Math.random() + 1) * 10000000000000;
    batch.value.skuNo = sn.toFixed(0);
  };
  
  // 上传图片成功
  const onUploadImgSuccess = (file, index) => {
    if (!file) {
      return;
    }
    const mockResponse = { data: { domain: 'https://example.com', fileName: 'image.jpg' } };
    props.skuData.skuList[index].logo = mockResponse.data.fileName;
    emits('skuChange', props.skuData);
  };
  
  // 生成表格数据
  const getTable = () => {
    const table = [];
    const attrValueAry = [];
    const arr = [];
    const tmpSkuData = (props.skuData.attrList || []).filter(
      (d) => d.name != "" && d.child.length > 0
    );
    if (!tmpSkuData || tmpSkuData.length == 0) {
      return [];
    }
  
    tmpSkuData.forEach((item) => {
      attrValueAry.push(item.child);
    });
  
    function func(skuArr = [], i) {
      for (let j = 0; j < attrValueAry[i].length; j++) {
        if (i < attrValueAry.length - 1) {
          skuArr[i] = attrValueAry[i][j];
          func(skuArr, i + 1);
        } else {
          arr.push([...skuArr, attrValueAry[i][j]]);
        }
      }
    }
    func([], 0);
  
    arr.forEach((item) => {
      let specIds = "",
        specList = [],
        findItem,
        tableItem;
      item.forEach((d) => {
        specIds += specIds ? `-${d.id}` : `${d.id}`;
        specList.push({ id: d.id, name: d.name, value: d.name });
      });
  
      findItem =
        props.skuData.initSkuList.find((item) => {
          return specIds.includes(item.specIds);
        }) || {};
  
      tableItem = Object.assign(
        {
          price: '',
          linePrice: '',
          skuNo: '',
          stock: '',
          logo: '',
          weight: '0',
          specList: specList
        },
        findItem,
        {
          specIds
        }
      );
      tableItem.specList = specList;
      table.push(tableItem);
    });
  
    return table;
  };
  </script>
  
  <style lang="scss" scoped>
  .sku-list {
    &-head {
      margin-bottom: 10px;
    }
    &-item {
      display: flex;
      align-items: center;
      border: 1px solid #eee;
      border-radius: 5px;
      margin-bottom: 5px;
      padding: 10px;
      background: #f5f5f5;
      &-main {
        flex: 1;
      }
      &-removeBtn {
        margin-left: 20px;
        color: #f56c6c;
      }
      &__layout {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        &:last-child {
          margin-bottom: 0;
        }
        .input {
          width: 240px;
        }
        .span {
          font-size: 13px;
          font-weight: bold;
          margin-right: 10px;
          color: #666;
        }
      }
      &-tags {
        flex: 1;
      }
      &-tag {
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }
  }
  .spec-tag {
    margin: 10px 0px 10px 0px;
    .i {
      background: #cceeee;
      color: #113a28;
      padding: 5px;
      border-radius: 12px;
    }
  }
  .sku-logo {
    height: 78px;
    width: 78px;
    border-radius: 6px;
  }
  .batch-setting {
    margin: 20px 0px 3px 0px;
    .input {
      width: 100px;
      margin-left: 10px;
    }
    .input-sn {
      width: 140px;
    }
    .button {
      margin-left: 5px;
    }
  }
  .create-sn {
    margin-left: 2px;
  }
  </style>    