<template>
  <div class="add-product-wrapper">
    <el-form label-width="108px" :model="form" ref="form" :rules="rules">
      <el-card style="margin: 20px 20px; font-size: 14px">
        <template v-slot:header>
          <div>
            <span>基本信息</span>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="outProductId">
              <el-input v-model="form.outProductId" placeholder="请输入商品编码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="品牌" prop="brandId">
              <brand-select v-model="form.brandId" @change="onBrandChange"></brand-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="categoryId">
              <el-cascader
                style="width: 100%"
                v-model="form.categoryId"
                :options="categoryOptions"
                :props="{
                  value: 'id',
                  label: 'name',
                  children: 'children',
                  checkStrictly: true,
                  emitPath: false
                }"
                placeholder="请选择分类"
                clearable
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" placeholder="请输入PRICE"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="form.weight" placeholder="商品重量，默认为克"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上架状态">
              <DictRadio v-model="form.publishStatus" radioData="pms_publish_status" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px">
        <template v-slot:header>
          <div>
            <span>产品图片</span>
          </div>
        </template>
        <el-form-item label="主图" prop="pic">
          <oss-image-upload v-model="form.pic" :limit="1"></oss-image-upload>
        </el-form-item>
        <el-form-item label="轮播图" prop="albumPics">
          <oss-image-upload v-model="albumPics" :limit="5" class="img-upload-mini"></oss-image-upload>
        </el-form-item>
      </el-card>

      <el-card style="margin: 20px 20px; font-size: 14px">
        <template v-slot:header>
          <div>
            <span>产品规格</span>
          </div>
        </template>
        <el-form-item label="规格类型">
          <div class="sku-wrapper">
            <div class="sku_sorts">
              <div :style="{ display: 'flex', width: '500px' }">
                <el-input v-model="nameAdd" placeholder="请输入要添加的规格名称（例如大小，版本，颜色）"></el-input>
                <el-button @click="addSkuSort" :style="{ marginLeft: '10px' }">+添加规格类型</el-button>
              </div>
              <div class="sku_sort" v-for="(s, idx0) in productAttr" :key="s.name">
                <div class="label flex-center">
                  <!-- <div class="flex-one">
                    <dict-select v-model="s.name" prop-name="sku_sort_list" value-prop="label"></dict-select>
                  </div> -->
                  <a class="red" @click="deleteSkuSort(idx0)">{{ s.name }}</a
                  ><span :style="{ color: 'blue', cursor: 'pointer', padding: '0 4px' }" @click="moveSpecGroupUp(s, idx0)" v-if="idx0 > 0">↑</span>
                  <span
                    :style="{ color: 'blue', cursor: 'pointer', padding: '0 4px' }"
                    @click="moveSpecGroupDown(s, idx0)"
                    v-if="idx0 < s.options.length - 1"
                    >↓</span
                  >
                </div>
                <div class="values" v-if="s.name">
                  <div :style="{ display: 'flex' }">
                    <div class="value" v-for="(it2, idx1) in s.options" :key="idx1">
                      <el-tag type="primary" v-if="idx1 != undefined">
                        <span>{{ it2.name }} </span>
                        <span :style="{ color: 'red', cursor: 'pointer', paddingLeft: '8px' }" @click="deleteOption(s, idx1)" v-if="idx1 != undefined"
                          >X</span
                        >
                      </el-tag>
                    </div>
                    <div :style="{ padding: '0 32px 8px 0', display: 'flex', alignItems: 'center', gap: '8px' }">
                      <el-input v-model="s.newOptionName" placeholder="请输入规格值"></el-input>
                      <el-tag type="primary">
                        <span @click="addOption(s, idx1)">添加</span>
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="规格信息">
          <el-button @click="refreshSku()" class="mb20">刷新列表</el-button>
          <el-table :data="form.skuList" :max-height="400" :span-method="objectSpanMethod">
            <el-table-column v-for="s in skuAttr" :label="s.name" :key="s.name" :prop="s.name"></el-table-column>
            <el-table-column label="展示图片">
              <template v-slot="{ row }">
                <oss-image-upload class="img-upload-mini" v-model="row.pic" :limit="1" :is-show-tip="false"></oss-image-upload>
              </template>
            </el-table-column>
            <el-table-column label="销售价格">
              <template v-slot="{ row, $index }">
                <el-form-item :rules="{ required: true, message: '请填写价格', trigger: 'blur' }" :prop="'skuList[' + $index + '].price'">
                  <el-input v-model="row.price"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="库存">
              <template v-slot="{ row, $index }">
                <el-input v-model="row.stock" type="number"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="编码">
              <template v-slot="{ row }">
                <el-form-item>
                  <el-input v-model="row.outSkuId"></el-input>
                  <el-input v-model="row.spData" v-show="false"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row, $index }">
                <el-form-item>
                  <el-button text type="primary" icon="Delete" @click="handleDeleteSku(row, $index)">删除</el-button>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-card>
      <el-card style="margin: 20px 20px; font-size: 14px">
        <template v-slot:header>
          <div>
            <span>详情页</span>
          </div>
        </template>
        <el-form-item label="移动端" prop="detailMobileHtml">
          <Editor v-model="form.detailMobileHtml" placeholder="请输入内容" type="url"></Editor>
        </el-form-item>
        <el-form-item label="PC端" prop="detailHtml">
          <Editor v-model="form.detailHtml" placeholder="请输入内容" type="url"></Editor>
        </el-form-item>
      </el-card>

      <div class="tc">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { addPmsProduct, getPmsProduct, updatePmsProduct } from '@/api/pms/product';
// import ProductCategorySelect from '@/views/components/ProductCategorySelect';
import BrandSelect from '@/views/components/BrandSelect';
import { listPmsProductCategory } from '@/api/pms/productCategory';
export default {
  name: 'AddProduct',
  dicts: ['pms_publish_status'],
  components: { BrandSelect },
  data() {
    return {
      color: '',
      nameAdd: '',
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }]
      },
      categoryOptions: [],
      form: {
        publishStatus: '',
        sort: 1000
      },
      skuAttr: [],
      albumPics: null,
      productAttr: [],
      maxOptionNum: 44
    };
  },
  created() {
    this.getSkuList();
    const { id } = this.$route.query;
    if (id) {
      this.getInfo(id);
    }
  },
  methods: {
    // 删除单个SKU
    handleDeleteSku(row, index) {
      this.$modal.confirm('确定要删除这个规格组合吗？').then(() => {
        // 只删除当前这一行
        console.log(this.form.skuList, index);
        this.form.skuList.splice(index, 1);
        this.$modal.success('删除成功');
      });
    },
    // 向上移动整个规格组
    moveSpecGroupUp(s, index) {
      if (index > 0) {
        const temp = this.productAttr[index];
        this.productAttr[index] = this.productAttr[index - 1];
        this.productAttr[index - 1] = temp;
        this.refreshSku(); // 重新生成SKU列表
      }
    },

    // 向下移动整个规格组
    moveSpecGroupDown(s, index) {
      if (index < this.productAttr.length - 1) {
        const temp = this.productAttr[index];
        this.productAttr[index] = this.productAttr[index + 1];
        this.productAttr[index + 1] = temp;
        this.refreshSku(); // 重新生成SKU列表
      }
    },
    // 完全替换现有的 objectSpanMethod 方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 只对规格列进行合并（排除图片、价格等操作列）
      if (columnIndex < this.skuAttr.length) {
        return this.calculateMultiLevelSpan(rowIndex, columnIndex);
      }
      return { rowspan: 1, colspan: 1 };
    },

    // 新增多级合并计算逻辑
    calculateMultiLevelSpan(rowIndex, columnIndex) {
      if (!this.form.skuList || this.form.skuList.length === 0) {
        return { rowspan: 1, colspan: 1 };
      }

      const currentRow = this.form.skuList[rowIndex];

      // 如果是第一列（最外层规格）
      if (columnIndex === 0) {
        const specName = this.skuAttr[0].name;
        const currentValue = currentRow[specName];

        // 找到这个值的起始行和结束行
        let startRow = rowIndex;
        let endRow = rowIndex;

        // 向上查找
        for (let i = rowIndex - 1; i >= 0; i--) {
          if (this.form.skuList[i][specName] === currentValue) {
            startRow = i;
          } else {
            break;
          }
        }

        // 向下查找
        for (let i = rowIndex + 1; i < this.form.skuList.length; i++) {
          if (this.form.skuList[i][specName] === currentValue) {
            endRow = i;
          } else {
            break;
          }
        }

        const rowspan = endRow - startRow + 1;

        // 只在起始行显示合并
        if (rowIndex === startRow) {
          return { rowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }

      // 对于其他列（内层规格）
      if (columnIndex > 0) {
        const specName = this.skuAttr[columnIndex].name;
        const currentValue = currentRow[specName];

        // 获取所有前置规格的值
        const prefixSpecs = {};
        for (let i = 0; i < columnIndex; i++) {
          prefixSpecs[this.skuAttr[i].name] = currentRow[this.skuAttr[i].name];
        }

        // 找到在当前前置规格组合下的相同值范围
        let startRow = rowIndex;
        let endRow = rowIndex;

        // 向上查找
        for (let i = rowIndex - 1; i >= 0; i--) {
          let match = true;
          for (const [key, value] of Object.entries(prefixSpecs)) {
            if (this.form.skuList[i][key] !== value) {
              match = false;
              break;
            }
          }
          if (match && this.form.skuList[i][specName] === currentValue) {
            startRow = i;
          } else {
            break;
          }
        }

        // 向下查找
        for (let i = rowIndex + 1; i < this.form.skuList.length; i++) {
          let match = true;
          for (const [key, value] of Object.entries(prefixSpecs)) {
            if (this.form.skuList[i][key] !== value) {
              match = false;
              break;
            }
          }
          if (match && this.form.skuList[i][specName] === currentValue) {
            endRow = i;
          } else {
            break;
          }
        }

        const rowspan = endRow - startRow + 1;

        // 只在起始行显示合并
        if (rowIndex === startRow) {
          return { rowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }

      return { rowspan: 1, colspan: 1 };
    },
    refreshSku() {
      let skus = [];
      const skuMap = new Map();
      this.skuAttr = [...this.productAttr];
      if (this.form.skuList) {
        this.form.skuList.forEach((sku) => {
          skuMap.set(sku.spData, sku);
        });
      }
      this.productAttr.forEach((attr, index) => {
        const attrSku = [];
        attr.options.forEach((option) => {
          if (!option.name) {
            return;
          }
          if (index === 0) {
            attrSku.push({ [attr.name]: option.name });
          } else {
            skus.forEach((it3) => {
              attrSku.push({ ...it3, [attr.name]: option.name });
            });
          }
        });
        skus = attrSku;
      });
      skus.forEach((it) => {
        if (it) {
          it.spData = JSON.stringify(it);
        }
      });
      skus.forEach((it) => {
        const sku = skuMap.get(it.spData);
        if (sku) {
          it.outSkuId = sku.outSkuId;
          it.price = sku.price;
          it.pic = sku.pic;
          it.stock = sku.stock;
          it.id = sku.id;
        } else {
          it.outSkuId = null;
          it.price = null;
          it.pic = null;
          it.stock = null;
          it.id = null;
        }
      });
      this.form.productAttr = JSON.stringify(this.productAttr);
      this.form.skuList = skus.sort((a, b) => {
        // 按规格顺序排序，确保合并正确
        for (let i = 0; i < this.skuAttr.length; i++) {
          const specName = this.skuAttr[i].name;
          if (a[specName] !== b[specName]) {
            return a[specName].localeCompare(b[specName]);
          }
        }
        return 0;
      });
      // this.form.skuList = skus;
    },
    categoryChange(value) {
      if (Array.isArray(value)) {
        this.form.productCategoryName = value.toString();
      } else {
        this.form.productCategoryName = null;
      }
    },
    onBrandChange(value) {
      this.form.brandName = value;
    },
    getInfo(id) {
      getPmsProduct(id).then((response) => {
        const { albumPics } = response.data;
        if (albumPics) {
          this.albumPics = albumPics.split(',');
        }
        this.form = response.data;
        this.form.publishStatus = this.form.publishStatus.toString();
        if (this.form.productAttr) {
          this.productAttr = JSON.parse(this.form.productAttr);
        }
        this.refreshSku();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.albumPics) {
            this.form.albumPics = this.albumPics.toString();
          }
          if (this.form.categoryId && Array.isArray(this.form.categoryId)) {
            this.form.categoryId = this.form.categoryId.pop();
          }
          //商品价格没填时取sku的最低价
          if (!this.form.price) {
            // this.form.price = Math.min.apply(
            //   Math,
            this.form.skuList.map((it) => it.price);
            // );
          }

          if (this.form.id != null) {
            updatePmsProduct(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
            });
          } else {
            addPmsProduct(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
            });
          }
          this.cancel();
        } else {
          if (this.form.name) {
            this.$alert('请填写规格价格', '提示', {
              confirmButtonText: '确定'
            });
          } else {
            this.$alert('请填写商品名称', '提示', {
              confirmButtonText: '确定'
            });
          }
        }
      });
    },
    cancel() {
      this.$tab.closeOpenPage({ path: '/pms/product' });
    },
    changeName(s, idx, val) {
      s.options[idx].name = val;
      if (s.options.length - 1 !== idx || s.options.length >= this.maxOptionNum) {
        return;
      }
      s.options.push({ name: null });
    },
    addSkuSort() {
      if (this.nameAdd != '') {
        this.productAttr.push({
          name: this.nameAdd,
          options: [],
          newOptionName: ''
        });
        this.nameAdd = '';
      } else {
        this.$modal.msgError(`请输入规格名称`);
      }
    },
    deleteSkuSort(idx) {
      this.productAttr.splice(idx, 1);
    },
    addOption(specGroup, index) {
      const newName = specGroup.newOptionName?.trim();
      if (!newName) {
        this.$modal.msgError('请输入规格值');
        return;
      }
      // 检查是否已存在
      const exists = specGroup.options.some((opt) => opt.name === newName);
      if (exists) {
        this.$modal.msgError('该规格已存在');
        return;
      }
      specGroup.options.push({ name: newName });
      specGroup.newOptionName = ''; // 清空输入框
      this.refreshSku();
    },

    deleteOption(specGroup, index) {
      specGroup.options.splice(index, 1);
      this.refreshSku();
    },
    getSkuList() {
      listPmsProductCategory({ id: null }).then((response) => {
        this.categoryOptions = response.data;
      });
    }
  }
};
</script>

<style lang="stylus">
.add-product-wrapper
  padding 12px
  .content
    margin 0 auto
    width 75%
    min-width 800px
  .sku-wrapper
    background-color #f7f8fa
    padding 12px
    .sku_sorts
      .sku_sort
        background-color white
        margin-bottom 12px
        .label
          padding 8px
        .values
          padding 8px 0 0 8px
          border-top 1px solid $border-color
          display flex
          flex-wrap wrap
          .value
            padding 0 32px 8px 0
            display flex
            align-items center
  .img-upload-mini .el-upload--picture-card
    width: 48px;
    height: 48px;
    line-height: 57px;
  .hide  .el-upload-list--picture-card .el-upload-list__item
      width: 80px;
      height: 80px;
      margin-bottom: 0;
      margin-right: 8px;
  .el-upload-list--picture-card .el-upload-list__item
    width: 80px;
    height:80px;
</style>
