<template>
  <!-- 多级 套餐商品信息 -->
  <div class="app-main-height">
    <el-tabs v-model="activeName" @tab-click="handleClick(activeName)">
      <el-tab-pane label="商品信息" name="first">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="20" :lg="25" :xl="8">
            <el-form
              ref="addGoods"
              :model="addGoods"
              label-width="100px"
              class="demo-ruleForm"
              :rules="rules"
            >
              <el-form-item label="选择分类" prop="classificationID">
                <GoodsClassification
                  :classificationid="addGoods.classificationID"
                  @choseGoodsType="choseGoodsType"
                />
              </el-form-item>
              <el-form-item label="商品名称" prop="goodsName">
                <el-input
                  v-model.trim="addGoods.goodsName"
                  placeholder="请输入商品名称"
                />
              </el-form-item>

              <el-form-item label="选择产地" prop="addr">
                <v-distpicker
                  ref="getprovince"
                  :provinceid.sync="addGoods.provinceID"
                  :cityid.sync="addGoods.cityID"
                  :countyid.sync="addGoods.countyID"
                  @getAreaCode="getAreaCode"
                />
              </el-form-item>
              <el-form-item label="供应商名称">
                <el-input
                  v-model="addGoods.providerName"
                  placeholder="请输入供应商名称"
                />
              </el-form-item>
              <el-form-item label="商品销量" prop="sales">
                <el-input
                  v-model.number="addGoods.sales"
                  placeholder="请输入商品销量,不填写则使用真实销量做展示"
                />
              </el-form-item>
              <el-form-item label="商品简介" prop="goodsOverview">
                <el-input
                  v-model="addGoods.goodsOverview"
                  type="textarea"
                  placeholder="简介"
                />
              </el-form-item>
              <el-form-item label="包邮说明">
                <el-input
                  v-model="addGoods.mailInstruction"
                  type="textarea"
                  placeholder="说明"
                />
              </el-form-item>
              <el-form-item label="商品主图" prop="images">
                <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :http-request="request"
                  :file-list="addGoods.images"
                  :before-upload="beforeUpload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :limit="5"
                  :on-exceed="handleExceed"
                  accept=".jpg, .jpeg, .png"
                  id="items"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <!-- <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="beforeUpload"
                  :file-list="addGoods.images"
                  :on-remove="handleRemove"
                  :limit="5"
                  :on-exceed="handleExceed"
                  accept=".jpg, .jpeg, .png"
                  id="items"
                >
                  <i class="el-icon-plus" />
                </el-upload> -->
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <P class="text"
                  >请保证图片尺寸为328*328,格式为jpg / jpeg / png的图片</P
                >
              </el-form-item>
              <el-form-item label="视频区">
                <div class="imgFile">
                  <el-button type="primary" size="mini"> 上传视频 </el-button>
                  <input
                    id="imgFile"
                    class="upload_input"
                    type="file"
                    accept="video/*"
                    @change="changeVideo($event)"
                  />
                </div>
                <video
                  v-if="videoUrl != ''"
                  :src="videoUrl"
                  controls="controls"
                  width="500"
                  height="400"
                />
                <el-button
                  v-if="videoUrl != ''"
                  type="text"
                  @click="handleUpdatevideo"
                  >删除</el-button
                >
                <p class="text">请保证视频格式正确，且不超过10M</p>
              </el-form-item>
              <el-form-item label="商品详情">
                <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :http-request="request1"
                  :before-upload="beforeUpload1"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove1"
                  :on-success="handleSuccess1"
                  :file-list="fileList"
                  :multiple="true"
                  accept=".jpg, .jpeg, .png"
                  id="items1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <!-- <el-upload
                  class="w-900"
                  action="#"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="beforeUpload1"
                  :file-list="addGoods.goodsDetaisImages"
                  :on-remove="handleRemove1"
                  :multiple="true"
                  id="items1"
                  accept=".jpg, .jpeg, .png"
                >
                  <i class="el-icon-plus" />
                </el-upload> -->
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
                <P class="text"
                  >请保证图片尺寸为328*328,格式为jpg / jpeg / png的图片</P
                >
              </el-form-item>
              <el-form-item>
                <el-button
                  :loading="loading"
                  type="primary"
                  @click.native.prevent="
                    $route.query.name === 'create'
                      ? submitForm('addGoods')
                      : editGoods('addGoods')
                  "
                >
                  保存并下一步
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="价格库存" name="second" :disabled="tabpane">
        <el-table :data="tableData">
          <template slot="empty">
            <p>{{ dataText }}</p>
          </template>
          <el-table-column prop="comboGoodsName" label="套餐名称" />
          <el-table-column prop="comboGoodsNum" label="库存" />

          <el-table-column prop="comboGoodsPrice" label="单价" />
          <el-table-column prop="comboCostPrice" label="成本价" />
        </el-table>
        <el-button
          type="primary"
          size="small"
          style="margin: 20px 0"
          @click="handlegoodsSubmit"
        >
          第三步录入三级
        </el-button>
      </el-tab-pane>
      <el-tab-pane label="商品规格" name="three" :disabled="tabpane">
        <!-- 商品规格 -->
        <div>
          <div style="padding: 10px 30px">
            <div class="goods-spec">
              <span>商品规格:</span>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  :disabled="privateGoodsItem.length >= 3"
                  @click="addPrivateSpec"
                  >添加规格
                </el-button>
                <el-button type="primary" size="small" @click="edit()"
                  >自定义排序
                </el-button>
              </div>
            </div>

            <div
              class="goods-container"
              v-for="(attr, index) in privateGoodsItem"
              :key="index"
            >
              <div class="goods-content">
                <div class="goods-content-box">
                  <div class="goods-content-left">
                    <el-form label-width="80px">
                      <el-form-item label="规格名">
                        <!-- <el-input v-model="attr.privateSpecName" placeholder="请输入规格名"></el-input> -->

                        <el-select
                          v-model="attr.privateSpecid"
                          placeholder="请选择"
                          size="mini"
                        >
                          <el-option
                            v-for="item in SpecificationsList"
                            :key="item.id"
                            :label="item.value"
                            :value="item.id"
                            v-show="!isdisabled(item.id)"
                          >
                          </el-option>
                        </el-select>
                        <el-checkbox v-model="haspic" v-if="index == 0"
                          >商品图</el-checkbox
                        >
                      </el-form-item>
                      <el-form-item label="规格值">
                        <div
                          v-for="(tag, index2) in attr.dynamicTags"
                          :key="index2"
                          style="float: left; margin-left: 10px"
                        >
                          <el-tag
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag, attr)"
                          >
                            {{ tag.spec_name }}
                          </el-tag>
                          <el-upload
                            v-if="haspic && index == 0 && images[index2]"
                            class="avatar-uploader"
                            action="/ronghui/admin/uploadFile"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess.bind(this, index2)"
                            :before-upload="beforeAvatarUpload"
                          >
                            <img
                              v-if="images[index2].imageUrl"
                              :src="images[index2].imageUrl"
                              class="avatar"
                            />
                            <i
                              v-else
                              class="el-icon-plus avatar-uploader-icon"
                            ></i>
                          </el-upload>
                        </div>
                        <!-- 当inputVisible为true时显示输入框 @blur="handleInputConfirm(attr.inputValue, attr)"-->
                        <el-input
                          class="input-new-tag"
                          v-if="attr.inputVisible"
                          v-model="attr.inputValue"
                          :ref="`saveTagInput${index}`"
                          size="small"
                          @keyup.enter.native="
                            handleInputConfirm(attr.inputValue, attr)
                          "
                        >
                        </el-input>
                        <!-- v-else-if="attr.dynamicTags.length<50" 当每个规格做的规格值小于50时才能添加规格值 -->
                        <!-- <el-button v-if="attr.inputVisible" size="small">关闭</el-button> -->
                        <el-button
                          v-if="attr.inputVisible"
                          size="small"
                          @click="handleInputConfirm(attr.inputValue, attr)"
                          >{{ attr.inputValue ? "保存" : "取消" }}</el-button
                        >
                        <el-button
                          v-else
                          class="button-new-tag"
                          size="small"
                          @click="showInput(attr, index)"
                          >+ 添加</el-button
                        >
                      </el-form-item>
                    </el-form>
                  </div>
                  <div
                    class="goods-content-right"
                    v-if="privateGoodsItem.length > 1"
                  >
                    <el-link type="danger" @click="delPrivateSpec(index, attr)"
                      >删除规格</el-link
                    >
                  </div>
                </div>
              </div>
            </div>

            <p style="margin: 24px 0 10px 0">规格明细：</p>
            <el-table
              ref="multipleTable"
              border
              :data="tableColumnList_now.tableBodyList"
              :highlight-current-row="false"
              style="width: 100%; margin-top: 1%"
              :span-method="objectSpanMethod"
            >
              <el-table-column
                :label="item.propName"
                :property="item.prop"
                v-for="item in tableColumnList_now.tableHeaderList"
                :key="item.prop"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row[scope.column.property].spec_name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="价格（元）">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.price"
                    @input="handleInput(scope.row.price, scope, 'price')"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- <el-table-column label="原价(划线价)">
                <template slot-scope="scope">
                  <el-input
                  v-model.trim="scope.row.line_price"
                  @input="
                    handleInput(scope.row.line_price, scope, 'line_price')
                  "
                  ></el-input>
                </template>
              </el-table-column> -->
              <el-table-column label="划线价">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.line_price"
                    @input="
                      handleInput(scope.row.line_price, scope, 'line_price')
                    "
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="库存">
                <template slot-scope="scope">
                  <el-input v-model.number="scope.row.stock"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="重量">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.weight"
                    @input="handleInput(scope.row.weight, scope, 'weight')"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="成本">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.cost_price"
                    @input="
                      handleInput(scope.row.cost_price, scope, 'cost_price')
                    "
                  ></el-input>
                </template>
              </el-table-column>

            </el-table>

            <div class="batches">
              批量设置:
              <div class="batches_content">
                <el-link
                  type="primary"
                  @click="show_batches_input = 'price'"
                  class="price_change"
                  v-if="!show_batches_input"
                >
                  批量设置价格</el-link
                >
                <el-link
                  type="primary"
                  @click="show_batches_input = 'stock'"
                  class="price_change"
                  v-if="!show_batches_input"
                >
                  批量设置库存</el-link
                >
                <el-link
                  type="primary"
                  @click="show_batches_input = 'weight'"
                  class="price_change"
                  v-if="!show_batches_input"
                >
                  批量设置重量</el-link
                >
                <el-link
                  type="primary"
                  @click="show_batches_input = 'cost_price'"
                  class="price_change"
                  v-if="!show_batches_input"
                  >批量设置成本</el-link
                >
                <el-link
                  type="primary"
                  @click="show_batches_input = 'line_price'"
                  class="price_change"
                  v-if="!show_batches_input"
                  >批量设置划线价</el-link
                >
                <div v-if="show_batches_input">
                  <el-input
                    v-model="num"
                    size="small"
                    style="width: 150px; margin-right: 10px"
                  >
                  </el-input>
                  <el-button type="primary" size="small" @click="savenum"
                    >保存</el-button
                  >
                  <el-button type="danger" size="small" @click="cancel"
                    >取消</el-button
                  >
                </div>
              </div>
            </div>
            <el-button
              type="primary"
              size="small"
              style="margin: 20px 0"
              @click="fourth"
            >
              提交审核
            </el-button>
            <!-- <el-button
              type="primary"
              size="small"
              style="margin: 20px 0"
              @click="fourth"
            >
              保存并下一步
            </el-button> -->
            
          </div>

          <el-dialog
            title="拖动规格值进行排序"
            :visible.sync="editdialogVisible"
            width="600px"
          >
            <div v-for="(attr, index) in privateGoodsItem_dialog" :key="index">
              <div class="tag_title">{{ attr.privateSpecName }}</div>
              <div class="tag_list">
                <!-- 拖动组件 -->
                <draggable
                  :list="attr.dynamicTags"
                  :options="{ group: 'title' + index, animation: 150 }"
                  :no-transition-on-drag="true"
                >
                  <transition-group type="transition">
                    <el-tag
                      style="margin-right: 10px"
                      v-for="(tag, index) in attr.dynamicTags"
                      :key="index"
                    >
                      {{ tag.spec_name }}
                    </el-tag>
                  </transition-group>
                </draggable>
              </div>
            </div>

            <span slot="footer" class="dialog-footer">
              <el-button @click="editdialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="edit_save">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-tab-pane>
      <!-- 第三个页 -->
      <!-- <el-tab-pane label="满额活动" name="fourth" :disabled="tabpane">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="20" :lg="25" :xl="8">
            <el-form
              ref="acti"
              :model="addGoods"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="是否参加活动">
                <el-radio-group v-model="full_activity" :disabled="disabled">
                    <el-radio label="1">
                        是
                    </el-radio>
                    <el-radio label="0">
                        否
                    </el-radio>
                </el-radio-group>
              </el-form-item>
              <div v-show="full_activity == 1">
                <el-form-item label="活动类型">
                  <el-select v-model="activity_type" placeholder="请选择分类" @change="chooseType()">
                    <el-option label="满额减" value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item label="活动名称">
                  <el-select v-model="activity_id" placeholder="请选择活动">
                    <el-option v-for="item in activity" :key="item.activity_id" :label="item.activity_name" :value="item.activity_id"/>
                  </el-select>
                </el-form-item>
                <div style="margin-left:100px;color:#999999;">{{activity_detail}}</div>
              </div>
            </el-form>
          </el-col>
        </el-row>
        <el-button
          type="primary"
          size="small"
          style="margin: 20px 0"
          @click="submit"
        >
          提交审核
        </el-button>
      </el-tab-pane> -->
    </el-tabs>
  </div>
</template>

<script>
import VDistpicker from "@/components/distpicker";
import newpackage from "../components/newpackage.vue";
import GoodsClassification from "@/components/GoodsClassification";
import { mapGetters } from "vuex";
import Sortable from "sortablejs";
// 引入防抖函数
import debounce from "lodash.debounce";
//拖动组件
import draggable from "vuedraggable";
import { exists } from "fs";
import { log } from "util";
import { sortKey } from "@/utils/data";
export default {
  name: "MoreLevelEditlist",
  components: { VDistpicker, newpackage, GoodsClassification, draggable },
  data() {
    const validategoodsName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品名称"));
      } else if (value.length > 40) {
        callback(new Error("商品名称长度不能超出40个字符"));
      } else {
        callback();
      }
    };
    const validateclassificationID = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择商品分类"));
      } else {
        callback();
      }
    };
    const validateaddr = (rule, value, callback) => {
      if (
        this.addGoods.provinceID === "" ||
        this.addGoods.cityID === ""
        // this.addGoods.countyID === ""
      ) {
        callback(new Error("请选择地区"));
      } else {
        callback();
      }
    };
    const validategoodsOverview = (rule, value, callback) => {
      if (value.length > 40) {
        callback(new Error("商品简介长度不能超出40个字符"));
      } else {
        callback();
      }
    };
    const validateimages = (rule, value, callback) => {
      if (this.addGoods.images.length <= 0) {
        callback(new Error("请上传商品主图"));
      } else {
        callback();
      }
    };
    return {
      remakeID: "",
      remake: "",
      loading: false,
      activeName: "first",
      videoFlag: false,
      dialogstatus: "",
      isupload: false,
      dialogImageUrl: "",
      dialogVisible: false,
      tabpane: false,
      imgUrl: [],
      disabled: false,
      dataText: "暂无数据",
      videoUrl: "",
      images: [],
      fileList: [], // 展示的商品详情
      beforeArr: [],
      addGoods: {
        classificationID: "",
        classificationName: "",
        provinceID: "",
        provinceName: "",
        cityID: "",
        cityName: "",
        countyID: "",
        countyName: "",
        goodsName: "",
        mailInstruction: "",
        goodsOverview: "",
        goodsDetais: "",
        video: "",
        images: [],
        goodsDetaisImages: [],
        providerName: "",
      },
      config2: {
        id: "mse2",
        url: "",
        volume: 1,
        autoplay: true,
      },
      Player2: null,
      config1: {
        id: "mse1",
        url: "",
        volume: 1,
        autoplay: false,
      },
      Player1: null,
      tableData: [],
      newList: [],
      temp: {
        goodsID: "",
        comboGoodsPrice: "",
        comboGoodsNum: "",
        comboGoodsName: "",
        comboGoodsID: "",
      },
      attend: "",
      full_activity: "",
      activity: {   // 活动
        activity_id: "",
        activity_name: "",
      },
      activity_id: "",
      activity_detail: "",
      activity_type: "",
      rules: {
        classificationID: [
          {
            required: true,
            trigger: "blur",
            validator: validateclassificationID,
          },
        ],
        addr: [{ required: true, trigger: "blur", validator: validateaddr }],
        goodsName: [
          { required: true, trigger: "blur", validator: validategoodsName },
        ],
        goodsOverview: [
          {
            required: false,
            trigger: "blur",
            validator: validategoodsOverview,
          },
        ],
        images: [
          { required: true, trigger: "blur", validator: validateimages },
        ],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "change",
          },
        ],
      },

      // 多级套餐规格
      SpecificationsList: [],
      //上次table的数据，是为了表格输入数据之后，修改规格，可以回显数据
      tableColumnList: {
        tableHeaderList: [],
        tableBodyList: [],
        // inventory: ''
      },
      //规格列表
      privateGoodsItem: [
        {
          privateSpecid: "", //规格id /选中的规格名对应id
          privateSpecName: "", //规格名 /选中的规格名
          dynamicTags: [], //规格值数组
          inputVisible: false, //是否显示为输入框
          inputValue: "",
        },
      ],
      //批量设置的那个数字
      num: null,
      //批量设置的状态[ price，stock，weight，cost_price]
      show_batches_input: false,
      //本次正在输入的table数据
      tableColumnList_now: {
        tableHeaderList: [],
        tableBodyList: [],
        // inventory: ''
      },
      //是否有图
      haspic: false,
      //图片列表
      images: [],
      //弹窗的展示
      editdialogVisible: false,
      //弹框里的数据，放置弹窗直接修改内容
      privateGoodsItem_dialog: [],
      drag: false,
      // 编辑三级套餐的id
      spec_merchantsId: "",
      // 删除规格值的id
      delArrId: [],
      // 删除大规格的数组
      delPrivateSpecDel: [],
      // 判断是 删除的大规格值还是小规格值 1大规格 2小规格
      big: 0,
      isEdit: false,
      // 全部套餐id
      idArr: [],
    };
  },
  computed: {
    ...mapGetters(["goodsID", "merchantsId", "goodstate"]),
    // 计算规格
    calculateAttribute() {
      // 初始化
      let obj = {};
      this.privateGoodsItem.forEach((item) => {
        // 判断有没有输入规格名
        if (item.privateSpecid && item.dynamicTags.length > 0) {
          //如果规格名字选中了，就找到这个id,找到汉字名
          for (var typeitem of this.SpecificationsList) {
            if (typeitem.id == item.privateSpecid) {
              item.privateSpecName = typeitem.value;
            }
          }
          //'颜色':'黄色'
          obj[item.privateSpecName] = item.dynamicTags;
        }
      });
      return obj;
    },
  },
  watch: {
    haspic(newval) {
      //如果选中了有图，那么就需要根据规格重新生成图片列表
      if (newval) {
        var length = this.privateGoodsItem[0].dynamicTags.length;
        this.images = [];
        for (var x = 0; x < length; x++) {
          this.images.push({
            name: this.privateGoodsItem[0].dynamicTags[x].spec_name,
            imageUrl: "",
            url: "",
          });
        }
      }
    },
    // 监听规格数据
    calculateAttribute(newVal) {
      if (JSON.stringify(newVal) == "{}") {
        this.tableColumnList_now.tableBodyList = [];
        this.tableColumnList_now.tableHeaderList = [];
        return;
      }
      //把图片数据更新一下
      var length = this.privateGoodsItem[0].dynamicTags.length;
      var now_imgs = JSON.parse(JSON.stringify(this.images));
      this.images = [];
      // 为什么使用下面的双重循环，是因为现在images和tag没有双向绑定，所以tag变化，images也应该变化
      /////////////////
      // test
      // return;

      //////////////
      for (var x = 0; x < length; x++) {
        //从图片里面看是否能找到name为这个的图片
        var find = false;
        for (var y = 0; y < now_imgs.length; y++) {
          //如果找到了相同名字的，那么该照片属于这个名字
          if (
            now_imgs[y].name ==
            this.privateGoodsItem[0].dynamicTags[x].spec_name
          ) {
            // alert(this.privateGoodsItem[0].dynamicTags[x].spec_name);
            find = true;
            this.images.push(now_imgs[y]);
          }
        }
        if (find == false) {
          this.images.push({
            name: this.privateGoodsItem[0].dynamicTags[x].spec_name,
            imageUrl: "",
            url: "",
          });
        }
      }
      // return;
      //图片更新结束
      let cloneNewVal = JSON.parse(JSON.stringify(newVal));
      let attrName = []; //规格名数组
      let attrValue = []; //规格值数组
      for (let key in cloneNewVal) {
        attrName.push(key);
        attrValue.push(cloneNewVal[key]);
      }
      // 表格内容数据（笛卡尔积算法）
      let finalArr = this.cartesianProductOf(...attrValue);
      let tableObj = {
        tableBodyList: [],
        tableHeaderList: [],
      };
      // 表格内容生成
      tableObj.tableBodyList = finalArr.map((item) => {
        var obj = (obj = {
          id: "",
          price: 0,
          stock: 0,
          weight: 0,
          cost_price: 0,
          line_price: 0,
          attrName: attrName,
          attrVal: item,
        });
        //查找上次数据是否有这条数据的值，如果有就要使用上次的值，不能只能使用
        var find = false;
        var nowdata = this.tableColumnList_now.tableBodyList;
        for (var x = 0; x < nowdata.length; x++) {
          if (
            JSON.stringify(nowdata[x].attrName) == JSON.stringify(attrName) &&
            JSON.stringify(nowdata[x].attrVal) == JSON.stringify(item)
          ) {
            find = true;
            obj = {
              id: this.tableColumnList_now.tableBodyList[x].id,
              price: this.tableColumnList_now.tableBodyList[x].price,
              stock: this.tableColumnList_now.tableBodyList[x].stock,
              weight: this.tableColumnList_now.tableBodyList[x].weight,
              cost_price: this.tableColumnList_now.tableBodyList[x].cost_price,
              line_price: this.tableColumnList_now.tableBodyList[x].line_price,
              attrName: attrName,
              attrVal: item,
            };

            x = nowdata.length;
          }
        }
        //查找上次数据并赋值结束
        for (let i = 0; i < item.length; i++) {
          obj[attrName[i]] = item[i];
        }
        return obj;
      });
      //接下来生成表格数据
      this.tableColumnList.tableBodyList = tableObj.tableBodyList; //表格内容数据备份
      this.tableColumnList_now.tableBodyList = [...tableObj.tableBodyList];
      // 表头
      let skuTableArr = Object.keys(newVal);
      tableObj.tableHeaderList = skuTableArr.map((item) => {
        return {
          prop: item,
          propName: item,
        };
      });
      this.tableColumnList.tableHeaderList = tableObj.tableHeaderList; // 表头数据备份
      this.tableColumnList_now.tableHeaderList = [...tableObj.tableHeaderList];
      // 表格内容生成
    },
  },
  created() {
    if (this.$route.query.name === "create") {
      this.tabpane = true;
      this.fileList = this.addGoods.goodsDetaisImages;
    } else if (this.$route.query.name === "update") {
      this.tabpane = false;
      this.getGoodsDetails();
      // 回显三级套餐
      this.getSpecMerchantsApi();
      // 回显拖动的值
      this.getSpecsSortAi();
      // 回显拖动得值
      this.getSpecsSortAi();
      // 回显活动信息
      // this.getGoodsFullActivityDetail();
    }
    this.addGoods.providerName = sessionStorage.getItem("providerName");
    // 三级套餐wa
    // 获取规格名
    this.getSpecsApi();
  },
  methods: {
    // 验证
    handleInput(value, scope, attr) {
      let resultValue = "";
      if (isNaN(value)) {
        if (isNaN(parseFloat(value))) {
          resultValue = "";
        } else {
          resultValue = parseFloat(value);
        }
      } else {
        resultValue = value;
      }
      scope.row[attr] = resultValue; /* 手动把最新值赋给form.numberText */
    },
    //商品主图切换位置
    setSort() {
      var el = document
        .getElementById("items")
        .querySelectorAll(".el-upload-list--picture-card")[0];
      var sortable = Sortable.create(el, {
        onUpdate: (event) => {
          let newIndex = event.newIndex, //新的索引
            oldIndex = event.oldIndex; //旧的索引
          if (newIndex > oldIndex) {
            el.insertBefore(el.children[newIndex], el.children[oldIndex]);
          } else {
            el.insertBefore(
              el.children[newIndex],
              el.children[oldIndex].nextSibling
            );
          }
          //列表数组更新
          let item = this.addGoods.images.splice(oldIndex, 1);
          this.addGoods.images.splice(newIndex, 0, item[0]);
        },
      });
    },
    //商品详情切换位置
    setSortgoodsDetais() {
      var el = document
        .getElementById("items1")
        .querySelectorAll(".el-upload-list--picture-card")[0];
      var sortable = Sortable.create(el, {
        onUpdate: (event) => {
          let newIndex = event.newIndex, //新的索引
            oldIndex = event.oldIndex; //旧的索引
          if (newIndex > oldIndex) {
            el.insertBefore(el.children[newIndex], el.children[oldIndex]);
          } else {
            el.insertBefore(
              el.children[newIndex],
              el.children[oldIndex].nextSibling
            );
          }
          //列表数组更新
          let item = this.addGoods.goodsDetaisImages.splice(oldIndex, 1);
          this.addGoods.goodsDetaisImages.splice(newIndex, 0, item[0]);
        },
      });
    },
    // 商品主图
    // 上传成功定义addGoods.images
    handleSuccess(res, file, fileList) {
	    this.addGoods.images.push(file);
      this.$nextTick(() => {
        this.setSort();
      });
    },
    // 上传失败
    handleError(err, file, fileList){
      this.$message({
        message: "上传文件失败，请重新上传",
        type: "error",
      });
    },
    // http-request
    request(params){
      let file = params.file;
      const fd = new FormData();
      fd.append("file", file);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        res.name = file.name;
        res.url = res.imgurl;
        params.onSuccess(res);
      }).catch((err)=>{
        params.onError(err);
      })
    },

    // 上传成功定义addGoods.goodsDetaisImages
    handleSuccess1(res, file, fileList) {
      this.beforeArr.forEach((item, index) => {
        if (item.uid == file.uid) {  // 与正确顺序的UID进行比对，添加进将要上传后台的数组
          this.addGoods.goodsDetaisImages.splice(index, 1, res);
          this.fileList.splice(index, 1, res);
        }
      });
      this.$nextTick(() => {
        this.setSortgoodsDetais();
      });
    },
    // http-request
    request1(params){
      const file = params.file;
      const fd = new FormData();
      fd.append("file", file);
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        res.name = file.name;
        res.url = res.imgurl;
        res.uid = file.uid;
        params.onSuccess(res);
      });
    },
    beforeUpload(e){
      const isLt50M = e.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      };
    },
    beforeUpload1(e){
      const isLt50M = e.size / 1024 / 1024 < 2;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 2M!",
          type: "error",
        });
        return false;
      };
      this.beforeArr.push(e);
      if(this.tabpane){
        this.addGoods.goodsDetaisImages.push(e);
      }
    },
    //图片上传之前调用做一些拦截限制
    // beforeUpload(e) {
    //   const isLt50M = e.size / 1024 / 1024 < 2;
    //   if (!isLt50M) {
    //     this.$message({
    //       message: "上传文件大小不能超过 2M!",
    //       type: "error",
    //     });
    //     return false;
    //   }
    //   const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
    //   const fd = new FormData();
    //   // fd.append("avatar_file", e);
    //   // fd.append("avatar_data", avatar_data);
    //   fd.append("file", e);
    //   this.$http.post(this.$api.uploadFile, fd).then((res) => {
    //     res.name = e.name;
    //     res.url = res.imgurl; //https://81ronggui.oss-cn-beijing.aliyuncs.com
    //     // this.dialogImageUrl = `https://81ronggui.oss-cn-beijing.aliyuncs.com${res.url}`;
    //     this.addGoods.images.push(res);
    //   });
    //   this.$nextTick(() => {
    //     this.setSort();
    //   });
    // },
    // beforeUpload1(e) {
    //   const isLt50M = e.size / 1024 / 1024 < 2;
    //   if (!isLt50M) {
    //     this.$message({
    //       message: "上传文件大小不能超过 2M!",
    //       type: "error",
    //     });
    //     return false;
    //   }
    //   const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
    //   const fd = new FormData();
    //   // fd.append("avatar_file", e);
    //   // fd.append("avatar_data", avatar_data);
    //   fd.append("file", e);
    //   this.$http.post(this.$api.uploadFile, fd).then((res) => {
    //     res.name = e.name;
    //     res.url = res.imgurl;
    //     this.dialogImageUrl = res.url;
    //     // this.dialogImageUrl = `https://81ronggui.oss-cn-beijing.aliyuncs.com${res.url}`;
    //     this.addGoods.goodsDetaisImages.push(res);
    //     this.$nextTick(() => {
    //       this.setSortgoodsDetais();
    //     });
    //   });
    // },
    // 图片删除
    handleRemove(file, fileList) {
      if (this.addGoods.images.indexOf(file) > -1) {
        const index = this.addGoods.images.findIndex((item) => {
          return item.uid === file.uid;
        }); 
        this.addGoods.images.splice(index, 1);
      }
    },
    // 图片删除
    handleRemove1(file, fileList) {
      if (this.addGoods.goodsDetaisImages.indexOf(file) > -1) {
        const index = this.addGoods.goodsDetaisImages.findIndex((item) => {
          return item.uid === file.uid;
        });
        this.addGoods.goodsDetaisImages.splice(index, 1);
      }
      if (this.beforeArr.indexOf(file) > -1) {
        const index = this.beforeArr.findIndex((item) => {
          return item.uid === file.uid;
        });
        this.beforeArr.splice(index, 1);
      }
    },
    // 保存并下一步
    submitForm(formName) {
      if (this.remake == "remake") {
        this.addGoods.goodsID = this.goodsID;
        this.editGoods("addGoods");
        return false;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.addGoods.merchantsID = this.merchantsId;
          const params = Object.assign(
            {},
            {
              type: "addGoods",
              data: this.addGoods,
            }
          );
          this.$store
            .dispatch("goods/addGoods", params)
            .then((response) => {
              this.activeName = "second";
              this.getComboList();
              this.remake = "remake";
              this.loading = false;
              this.tabpane = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName("is-error");
            isError[0].querySelector("input").focus();
          }, 100);
          this.loading = false;
          return false;
        }
      });
    },
    // 添加主推商品
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传5张`);
    },
    // 商品提交审核
    handlegoodsSubmit() {
      // const params = {
      //   type: "goodsSubmit",
      //   data: {
      //     goodsID: this.goodsID,
      //   },
      // };
      // this.$http.post(this.$api.goodsSubmit, params).then((res) => {
      //   this.$router.push({ path: "/Commoditymanagement/Commoditylist" });
      // });
      this.activeName = "three";
    },
    // 获取商品详情
    async getGoodsDetails() {
      const params = {
        type: "getGoodsDetails",
        data: {
          goodsID: this.goodsID,
        },
      };
      await this.$http.post(this.$api.getGoodsDetails, params).then((res) => {
        console.log(res)
        this.addGoods = res;
        this.fileList = res.goodsDetaisImages != '' ? res.goodsDetaisImages : [];
        this.beforeArr = res.goodsDetaisImages != '' ? res.goodsDetaisImages : [];
        res.providerName == "" || !this.addGoods.providerName
          ? (this.addGoods.providerName =
              sessionStorage.getItem("providerName"))
          : res.providerName;
        if (this.addGoods.images === "") {
          this.addGoods.images = [];
        } else {
          this.$nextTick(() => {
            this.setSort();
          });
        }
        if (this.addGoods.goodsDetaisImages === "") {
          this.addGoods.goodsDetaisImages = [];
        } else {
          this.$nextTick(() => {
            this.setSortgoodsDetais();
          });
        }
        if (res.video === "") {
          this.videoUrl = "";
          this.addGoods.video = "";
        } else {
          this.videoUrl = res.video.url;
          this.addGoods.video = res.video.imgurl;
        }
      });
    },
    // 上传视频
    changeVideo(e) {
      const current = e.target.files[0];
      if (!(current.size / 1024 / 1024 < 10)) {
        this.$message.error("上传视频大小不能超过10MB哦!");
      }
      const avatar_data = '{"x":0,"y":0,"height":100,"width":100,"rotate":0}';
      const fd = new FormData();
      fd.append("avatar_file", current);
      fd.append("avatar_data", avatar_data);
      // fd.append("file", e);  uploadAvatar  uploadFile
      this.$http.post(this.$api.uploadFile, fd).then((res) => {
        this.addGoods.video = res.imgurl;
        this.videoUrl = res.url;
      });
    },
    // 头部选择
    handleClick(activeName) {
      if (this.activeName === "second") {
        this.getComboList();
      }
    },
    // 获取商品套餐列表
    getComboList() {
      const params = {
        type: "getComboList",
        data: {
          goodsID: this.goodsID,
        },
      };
      this.$http.post(this.$api.getComboList, params).then((res) => {
        if (res.combos.length > 0) {
          this.tableData = res.combos;
          this.remakeID;
        } else {
          this.tableData = [];
        }
      });
    },
    handleDelete(row, index) {
      if (this.goodstate === "1" || this.goodstate === "0") {
        if (this.tableData.length <= 1) {
          this.$baseConfirm(
            "商品最后一个套餐被删除后，商品进入已下架状态，请确认是否继续操作!",
            null,
            async () => {
              this.delComboGoods(row, index);
            }
          );
        } else {
          this.$baseConfirm(
            "删除套餐后，该商品套餐将不在小程序显示。请确认是否继续操作!",
            null,
            async () => {
              this.delComboGoods(row, index);
            }
          );
        }
      } else {
        this.delComboGoods(row, index);
      }
    },
    // 删除商品套餐
    delComboGoods(row, index) {
      const params = {
        type: "delComboGoods",
        data: {
          comboGoodsID: row.comboGoodsID,
        },
      };
      this.$http.post(this.$api.delComboGoods, params).then((res) => {
        this.getComboList();
        this.$baseMessage("删除成功", "success");
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getList($event) {
      if (this.dialogstatus === "update") {
        this.getComboList();
      } else {
        this.getComboList();
      }
    },
    // 新增套餐
    handleCreate() {
      this.dialogstatus = "create";
      this.$nextTick(() => {
        this.$refs["newpackage"].showEdit();
      });
    },
    // 编辑套餐
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogstatus = "update";
      this.$nextTick(() => {
        this.$refs["newpackage"].showEdit(this.temp);
      });
    },
    // 获取商品分类
    choseGoodsType(obj) {
      this.addGoods.classificationID = obj.goodsClassificationID;
      this.addGoods.classificationName = obj.goodsClassificationName;
    },
    // 视频删除
    handleUpdatevideo() {
      this.addGoods.video = "";
      this.videoUrl = "";
    },
    // 获取省市区
    getAreaCode(area) {
      switch (area.key) {
        case "city":
          this.addGoods.provinceID = area.obj.id;
          this.addGoods.provinceName = area.obj.name;
          break;
        case "street":
          this.addGoods.cityID = area.obj.id;
          this.addGoods.cityName = area.obj.name;
          break;
        case "village":
          this.addGoods.countyID = area.obj.id;
          this.addGoods.countyName = area.obj.name;
          break;
      }
    },
    // 编辑商品
    editGoods(formName) {
      this.addGoods.providerName == "" ? (this.addGoods.providerName = sessionStorage.getItem("providerName")) : true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.addGoods.merchantsID = this.merchantsId;
          const params = {
            type: "editGoods",
            data: this.addGoods,
          };
          if (this.goodstate === "1") {
            this.$baseConfirm(
              "商品信息修改，商品将下架，请重新提交审核!",
              null,
              async () => {
                this.$store
                  .dispatch("goods/editGoods", params)
                  .then((response) => {
                    this.activeName = "second";
                    this.getComboList();
                    this.loading = false;
                  });
              }
            );
            this.loading = false;
          } else if (this.goodstate === "0") {
            this.$baseConfirm(
              "商品信息修改，商品将下架，请重新提交审核!",
              null,
              async () => {
                this.$store
                  .dispatch("goods/editGoods", params)
                  .then((response) => {
                    this.activeName = "second";
                    this.getComboList();
                  });
              }
            );
            this.loading = false;
          } else {
            this.$store
              .dispatch("goods/editGoods", params)
              .then((response) => {
                this.activeName = "second";
                this.getComboList();
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName("is-error");
            isError[0].querySelector("input").focus();
          }, 100);
          this.loading = false;
          return false;
        }
      });
    },

    // 多级套餐规格
    // 获取规格
    getSpecsApi() {
      let params = {
        type: "getSpecs",
        data: {},
      };
      this.$http.post(this.$api.getSpecs, params).then((res) => {
        res.forEach((e) => {
          this.SpecificationsList.push({ id: e.spec_id, value: e.spec_name });
        });
      });
    },
    //用来判断选中是否不能选中/选中的下个规格就禁用
    //循环下拉框数组,当下拉框数组有这个id并且与传递的id相等时就禁用
    isdisabled(id) {
      for (var item of this.privateGoodsItem) {
        if (item.privateSpecid && item.privateSpecid == id) {
          return true;
        }
      }
      return false;
    },
    //弹窗数据点击保存后把数据复制给当前展示使用的privateGoodsItem
    edit_save() {
      this.editdialogVisible = false;
      this.privateGoodsItem = JSON.parse(
        JSON.stringify(this.privateGoodsItem_dialog)
      );
      // 弹窗拖动元素的排序
      let editSpecsSortObj = {};
      let aggregateArr = [];
      let oneArr = [];
      let towArr = [];
      let threeArr = [];
      for (let i in this.calculateAttribute) {
        aggregateArr.push(this.calculateAttribute[i]);
      }
      // 向后台 传递参数格式处理 第一项规格
      if (aggregateArr.length == 1 || aggregateArr.length > 1) {
        aggregateArr[0].forEach((el, i) => {
          oneArr.push({
            sort: i,
            spec_value_id: el.spec_valueId ? el.spec_valueId : "",
          });
        });
      }
      // 第二项规格
      if (aggregateArr.length == 2 || aggregateArr.length > 2) {
        aggregateArr[1].forEach((el, i) => {
          towArr.push({
            sort: i,
            spec_value_id: el.spec_valueId ? el.spec_valueId : "",
          });
        });
      }
      // 第三项规格
      if (aggregateArr.length == 3) {
        aggregateArr[2].forEach((el, i) => {
          threeArr.push({
            sort: i,
            spec_value_id: el.spec_valueId ? el.spec_valueId : "",
          });
        });
      }
      editSpecsSortObj.first_spec_value = oneArr;
      editSpecsSortObj.second_spec_value = towArr;
      editSpecsSortObj.third_spec_value = threeArr;
      let params = {
        type: "editSpecsSort",
        data: {
          sort_JsonObj: editSpecsSortObj,
        },
      };
      this.$http.post(this.$api.editSpecsSort, params).then((res) => {
        // console.log("拖动排序", res);
        // console.log("editSpecsSortObj", editSpecsSortObj);
      });
    },
    // 回显拖动规格
    getSpecsSortAi() {
      const params = {
        type: "getSpecsSort",
        data: {
          goods_id: this.goodsID,
        },
      };
      this.$http.post(this.$api.getSpecsSort, params).then((res) => {
        // console.log("回显的拖动规格值", res);
      });
    },
    //弹窗弹出，把当前页面的privateGoodsItem数据，赋值给弹框
    edit() {
      this.privateGoodsItem_dialog = JSON.parse(
        JSON.stringify(this.privateGoodsItem)
      );
      this.editdialogVisible = true;
    },
    //图片成功上传，
    handleAvatarSuccess(idx, res, file) {
      this.images[idx].imageUrl = res.resultBody.imgurl;
      this.images[idx].url = res.resultBody.url;
    },
    //图片上传前验证
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      // const isJPG = file.type === "jpg";
      let type = file.name.substring(file.name.lastIndexOf(".") + 1);
      let ImgType =
        type === "jpg" ||
        type === "JPG" ||
        type === "png" ||
        type === "PNG" ||
        type === "bpm" ||
        type === "BPM" ||
        type === "jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!ImgType) {
        this.$message.error("上传头像图片只能是 jpg / png / bpm 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return ImgType && isLt2M;
    },
    // 添加规格
    addPrivateSpec(index) {
      this.privateGoodsItem.push({
        privateSpecName: "",
        dynamicTags: [],
        inputVisible: false,
        inputValue: "",
      });
    },
    //删除规格
    delPrivateSpec(index, item) {
      this.big = 1;
      this.delPrivateSpecDel = item.dynamicTags.map((el) => {
        return el.spec_valueId;
      });
      this.privateGoodsItem.splice(index, 1);
    },
    //当规格的input框失去焦点之后执行，在指定的规格下添加规格值
    handleInputConfirm(val, attr) {
      //当前tag当找不到相同的话才能添加
      // for (var x in item.dynamicTags) {
      //   if (item.dynamicTags[x].spec_name == val) {
      //     item.dynamicTags.splice(x, 1);
      //   }
      // }
      var finsarr = attr.dynamicTags.filter((item) => {
        return item.spec_name == val;
      });
      if (finsarr.length > 0) {
        this.$message.warning("您添加的规格值已经存在");
      }
      if (val && finsarr.length == 0) {
        attr.dynamicTags.push({ spec_name: val, spec_valueId: "" });
      }
      /////
      // if (val && attr.dynamicTags.indexOf(val) == -1) {
      //   attr.dynamicTags.push({ spec_name: val, spec_valueId: "" });
      // }
      attr.inputVisible = false;
      attr.inputValue = "";
    },
    //规格值的删除 tag:当前循环的每一项, item第一层循环的每一项
    handleClose(tag, item) {
      this.big = 2;
      this.delArrId.push(tag.spec_valueId);
      for (var x in item.dynamicTags) {
        if (item.dynamicTags[x].spec_name == tag.spec_name) {
          item.dynamicTags.splice(x, 1);
        }
      }
    },
    // 点击添加规格值
    showInput(attr, index) {
      // 当inputVisible为true时显示输入框
      attr.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs[`saveTagInput${index}`][0].$refs.input.focus();
      });
    },
    // 笛卡尔积算法，很重要，千万不要删除，
    cartesianProductOf(...args) {
      return args.reduce(
        (total, current) => {
          let ret = [];
          total.forEach((a) => {
            current.forEach((b) => {
              ret.push(a.concat([b]));
            });
          });
          return ret;
        },
        [[]]
      );
    },
    //用来展示时候合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      var privateGoodsItem = this.privateGoodsItem.filter((item) => {
        return item.privateSpecid && item.dynamicTags.length > 0;
      });

      var rownum = 1;
      for (var x = columnIndex + 1; x < privateGoodsItem.length; x++) {
        if (
          privateGoodsItem[x] &&
          privateGoodsItem[x].privateSpecid &&
          privateGoodsItem[x].dynamicTags.length > 0
        ) {
          rownum *= privateGoodsItem[x].dynamicTags.length;
        }
      }

      if (privateGoodsItem[columnIndex]) {
        if (rowIndex % rownum == 0) {
          return {
            rowspan: rownum,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1,
        };
      }
      return {
        rowspan: 2,
        colspan: 1,
      };
    },
    savenum() {
      if (this.num) {
        for (var x in this.tableColumnList.tableBodyList) {
          this.tableColumnList.tableBodyList[x][this.show_batches_input] =
            this.num;
        }
        this.show_batches_input = "";
        this.num = "";
      }
    },
    cancel() {
      this.show_batches_input = "";
      this.num = "";
    },
    // 删除大小规格判断
    judge() {
      if (this.big == 1) {
        // 删除规格id
        return this.delPrivateSpecDel;
      } else if (this.big == 2) {
        // 删除规格值数组id
        return this.delArrId;
      } else {
        return null;
      }
    },
    fourth: debounce(function () {
      // privateGoodsItem 选中的规格
      // tableColumnList_now  有下面的生成的表格数据
      // haspic  一级规格是否添加图片的开关
      // images  上传的图片
      // 上传时的套餐id数组
      let BequeathArr = [];
      this.tableColumnList_now.tableBodyList.filter((item) => {
        // 当有规格值删除事件发生时,添加删除的id
        if (this.big == 2) {
          BequeathArr.push(item.id);
        }
      });
      // 删除的套餐id
      let delArr = [];
      if (this.big == 2) {
        delArr = this.idArr.filter((item) => {
          return !BequeathArr.includes(item);
        });
      }
      // return;
      // 判断是否是空值，空值不让提交
      if (
        !this.privateGoodsItem[0].privateSpecName ||
        this.privateGoodsItem[0].dynamicTags.length == 0
      ) {
        return this.$message.error("请填写商品规格");
      } else if (this.haspic) {
        //图片提示
        let err = this.images.find((el) => {
          return el.imageUrl == "";
        });
        if (err) {
          return this.$message.error("请上传图片");
        }
      }
      // 第一级规格需要上传的数据
      let first_arr = [];
      // 将第一级规格的每一项添加到数组中
      if (this.privateGoodsItem[0] && this.privateGoodsItem[0].dynamicTags != null) {
        this.privateGoodsItem[0].dynamicTags.forEach((e) => {
          first_arr.push({
            spec_name: e.spec_name,
            spec_valueId: e.spec_valueId ? e.spec_valueId : "",
          })
        })
      };
      // 将每项图片添加到 一级规格的数组中
      first_arr.forEach((out) => {
        this.images.forEach((inner) => {
          if (out.spec_name == inner.name) {
            out.spec_img = inner.imageUrl;
          }
        })
      });
      // 一级套餐详情
      let tableBodyListArr = [];
      this.tableColumnList_now.tableBodyList.forEach((out) => {
        tableBodyListArr.push(out);
      });
      // 把每一项的规格名从数组中提取出来放到对象中
      tableBodyListArr.forEach((e) => {
        if (e.attrVal[0]) {
          e.first_spec_name = e.attrVal[0].spec_name ? e.attrVal[0].spec_name : "";
        }
        e.second_spec_name = e.attrVal[1] ? e.attrVal[1].spec_name : "";
        e.third_spec_name = e.attrVal[2] ? e.attrVal[2].spec_name : "";
        e.goods_num = e.stock;
        // delete e.attrName;
        // delete e.attrVal;
        // delete e.stock;
        e.id = e.id ? e.id : "";
      });
      // 二级规格
      let econd_arr = [];
      // 将第二级规格的每一项添加到数组中  e.spec_valueId ? e.spec_valueId :
      if (this.privateGoodsItem[1] != null && this.privateGoodsItem[1].dynamicTags != null) {
        this.privateGoodsItem[1].dynamicTags.forEach((e) => {
          econd_arr.push({
            spec_name: e.spec_name,
            spec_valueId: e.spec_valueId ? e.spec_valueId : "",
          });
        });
      }

      // 三级规格
      let third_arr = [];
      // 将第三级规格的每一项添加到数组中
      if (this.privateGoodsItem[2] != null && this.privateGoodsItem[2].dynamicTags != null) {
        this.privateGoodsItem[2].dynamicTags.forEach((e) => {
          third_arr.push({
            spec_name: e.spec_name,
            spec_valueId: e.spec_valueId ? e.spec_valueId : "",
          });
        });
      };
      for(let i in tableBodyListArr){
        if(tableBodyListArr[i].price <= 0){
          return this.$message.error("请填写价格");
        }
      };
      let params = {
        type: "addOrEditSpecMerchants",
        data: {
          // 商品ID
          goods_id: this.goodsID,
          // 一级规格ID
          first_specId: this.privateGoodsItem[0].privateSpecid ? this.privateGoodsItem[0].privateSpecid : "",
          // 一级规格名
          first_specName: this.privateGoodsItem[0].privateSpecName,
          // 一级规格属性
          first_specValue: first_arr,
          // 二级规格ID
          second_specId: this.privateGoodsItem[1] != null ? this.privateGoodsItem[1].privateSpecid ? this.privateGoodsItem[1].privateSpecid : "" : null,
          // 二级规格名
          second_specName: this.privateGoodsItem[1] != null ? this.privateGoodsItem[1].privateSpecName : null,
          // 二级规格属性
          second_specValue: econd_arr,
          // 三级规格ID
          third_specId:
            this.privateGoodsItem[2] != null ? this.privateGoodsItem[2].privateSpecid ? this.privateGoodsItem[2].privateSpecid : "" : null,
          // 三级规格名
          third_specName: this.privateGoodsItem[2] != null ? this.privateGoodsItem[2].privateSpecName : null,
          // 二级规格属性
          third_specValue: third_arr,
          // 套餐详情
          combo_good_detail: tableBodyListArr,
          spec_merchantsId: this.spec_merchantsId ? this.spec_merchantsId : "",
          // 删除规格值得id数组
          deleteIds: this.judge(),
          // 删除的套餐id
          deleteComboIds: delArr,
        },
      };
      this.$http.post(this.$api.addOrEditSpecMerchants, params).then((res) => {
        if (!res) {
          // 跳转到多级套餐列表;
          // this.activeName = "fourth";
          this.$router.push({ name: "CommoditymanagementMoreLevel" });
        }
      });
    }, 2000),
    // 选择活动分类
    chooseType(){
      if(this.activity_type == ''){
        this.activity_type = "1";
      };
      let params = {
        type: "getActivityMenus",
        data: {
          type: this.activity_type,
        },
      };
      this.$http.post(this.$api.getActivityMenus, params).then((res) => {
        this.activity = res
      });
    },
    // submit(){
    //   let params = {
    //     type: "addFullActivity",
    //     data: {
    //       goods_id: this.goodsID,
    //       full_activity: this.full_activity,
    //       activity_id: this.activity_id,
    //     },
    //   };
    //   this.$http.post(this.$api.addFullActivity, params).then((res) => {
    //     if (!res) {
    //       // 跳转到多级套餐列表;
    //       this.$router.push({ name: "CommoditymanagementMoreLevel" });
    //     }
    //   });
    // },
    // 回显三级套餐
    getSpecMerchantsApi() {
      let params = {
        type: "getSpecMerchants",
        data: {
          goods_id: this.goodsID,
        },
      };
      this.$http.post(this.$api.getSpecMerchants, params).then((res) => {
        res.combo_good_detail.filter((e) => {
          this.idArr.push(e.id);
        });
        // 编辑id
        this.spec_merchantsId = res.spec_merchantsId;
        this.isEdit = true;
        // 一级规格名回显spec_valueId
        this.privateGoodsItem[0].privateSpecName = res.first_specName;
        this.privateGoodsItem[0].privateSpecid = res.first_specId;
        this.privateGoodsItem[0].inputVisible = false;
        let imgArr = [];
        res.first_specValue.forEach((e) => {
          imgArr.push({
            imageUrl: e.spec_img,
            name: e.spec_name,
            url: e.spec_img,
          });
          this.privateGoodsItem[0].dynamicTags.push({
            spec_name: e.spec_name,
            spec_valueId: e.spec_valueId,
          });
          // this.privateGoodsItem[0].privateSpecid = e.spec_id;
          // 一级规格回显
          if (e.spec_img) {
            this.haspic = true;
            this.$nextTick(function () {
              this.images = [];
              this.images = imgArr;
            });
          }
        });
        // 二级规格回显,
        if (res.second_specId) {
          this.privateGoodsItem.push({
            privateSpecName: res.second_specName,
            privateSpecid: res.second_specId,
            dynamicTags: [],
            inputVisible: false,
          });
          this.privateGoodsItem[1].privateSpecid = res.second_specId;
          res.second_specValue.forEach((e) => {
            this.privateGoodsItem[1].dynamicTags.push({
              spec_name: e.spec_name,
              spec_valueId: e.spec_valueId,
            });
          });
        }

        // 三级回显
        if (res.third_specId) {
          this.privateGoodsItem.push({
            privateSpecName: res.third_specName,
            privateSpecid: res.third_specId,
            dynamicTags: [],
            inputVisible: false,
          });
          this.privateGoodsItem[2].privateSpecid = res.third_specId;
          res.third_specValue.forEach((e) => {
            this.privateGoodsItem[2].dynamicTags.push({
              spec_name: e.spec_name,
              spec_valueId: e.spec_valueId,
            });
          });
        }

        // 下面表格回显
        // this.tableColumnList_now.tableBodyList;

        this.$nextTick(function () {
          for (var item of this.tableColumnList_now.tableBodyList) {
            for (var goods of res.combo_good_detail) {
              var goods_attr = [
                goods.first_spec_name,
                goods.second_spec_name,
                goods.third_spec_name,
              ];
              goods_attr = goods_attr.filter((item) => {
                return item != "";
              });

              var table_tr_attr = [];
              for (var x in item.attrVal) {
                table_tr_attr.push(item.attrVal[x].spec_name);
              }
              if (goods_attr.toString() == table_tr_attr.toString()) {
                item.cost_price = goods.cost_price;
                item.price = goods.price;
                item.stock = goods.goods_num;
                item.weight = goods.weight;
                item.id = goods.id;
                item.line_price = goods.line_price;
                // item.attrName = goods_attrname;
                // item.attrVal = {
                // spec_name: goods.second_spec_name,
                // spec_valueId:
                // };
              }
            }
          }
        });
      });
    },
    // 回显满额活动
    getGoodsFullActivityDetail (){
      let params = {
        type: "getGoodsFullActivityDetail",
        data: {
          goods_id: this.goodsID,
        },
      };
      this.$http.post(this.$api.getSpecMerchants, params).then((res) => {
        this.full_activity = res.full_activity
        this.activity_id = res.activity_id
        this.activity_type = res.activity_type
        this.activity_detail = res.activity_detail
        this.chooseType();
      })
    }
  },
};
</script>
<style scoped>
.w-900 >>> .el-upload-list__item-name {
  position: absolute;
  display: inline-block;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  text-align: center;
  color: white;
  font-size: 13px;
  background: rgba(0, 0, 0, 0.5);
}
.w-900 >>> .el-upload-list__item-name .el-icon-document:before {
  content: "";
}
</style>
<style lang="scss" scoped>
.app-main-height {
  .el-select {
    margin-right: 15px !important;
  }
  .el-input {
    width: 400px;
  }
  .el-textarea {
    width: 400px;
  }
}
.imgFile {
  width: 98px;
  height: 40px;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
  input {
    position: absolute;
    opacity: 0;
    left: 0;
    top: 0;
    width: 98px;
    height: 40px;
  }
}
.ql-toolbar {
  .ql-container {
    height: 500px;
  }
}
.text {
  color: #333;
  font-size: 12px;
}
.w-900 {
  width: 900px !important;
}
// 多级套餐规格样式
.el-dialog__body {
  padding: 0 20px;
}

.tag_title {
  line-height: 3;
}

.tag_list {
  padding-left: 10px;
}

/* 图片上传的样式 */
.avatar-uploader {
  width: 100px;
  height: 100px;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

::v-deep .avatar-uploader-icon {
  font-size: 14px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

/* 页面样式 */
.goods-spec {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.goods-spec .goods-spec-add {
  margin-right: 15px;
}

.goods-container .button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.goods-container .input-new-tag {
  width: 90px;
  margin-right: 10px;
  vertical-align: bottom;
}

.goods-container .el-tag {
  margin-right: 10px;
}

.goods-container .goods-content {
  margin-bottom: 10px;
  padding: 14px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fcfcfc;
}

.goods-content .goods-content-box {
  display: flex;
  align-items: center;
}

.goods-content-box .goods-content-left {
  flex: 1;
}

.batches {
  padding: 10px 0;
}

.batches_content {
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 14px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fcfcfc;
}
.batches_content .price_change {
  margin-right: 10px;
}
</style>
