<!--添加基础资料-->
<template>
  <ContainerTit>
    <div slot="headr">
      <el-button class="bottom-btn" @click="tagLast">上一步</el-button>
      <el-button
        v-if="page_tabs !== '3'"
        class="bottom-btn"
        type="primary"
        @click="tagNext"
      >
        下一步
      </el-button>
      <el-button
        v-if="page_tabs === '3'"
        class="bottom-btn"
        type="primary"
        :loading="loading"
        @click="submitGoods"
      >
        完成，提交发布
      </el-button>
    </div>
    <div class="order_top">
      <div class="order_top_content">
        <el-steps :active="step_active" align-center>
          <el-step title="商品信息" icon="el-icon-document"></el-step>
          <el-step title="商品图集" icon="el-icon-picture-outline"></el-step>
          <el-step title="商品属性" icon="el-icon-document"></el-step>
        </el-steps>
      </div>
    </div>
    <div class="order_midden">
      <div class="goods-tab-view">
        <div class="btn-view">
          <el-button v-if="!base_goods_id" @click="delPauseSave(1)">
            清空缓存
          </el-button>
          <el-button v-if="!base_goods_id" @click="AddTem">暂存</el-button>
          <el-button
            v-if="$route.name !== 'BaseDataDetail'"
            type="primary"
            :loading="loading"
            @click="submitGoods"
          >
            保存
          </el-button>
        </div>
        <el-tabs v-model="page_tabs" @tab-click="tabClick">
          <el-tab-pane label="商品信息" name="1"></el-tab-pane>
          <el-tab-pane label="商品图集" name="2"></el-tab-pane>
          <el-tab-pane label="商品属性" name="3"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="detail-tab-item">
        <el-form
          v-show="page_tabs === '1'"
          ref="base_form"
          :model="base_form"
          label-width="120px"
          :rules="base_rules"
          size="small"
        >
          <div class="detail-tab-main">
            <el-row>
              <el-col :span="24">
                <p class="order_midden_left_text">
                  <span class="el-icon-arrow-right"></span>
                  <span>商品信息</span>
                </p>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品名称：" prop="title">
                  <el-input
                    v-model="base_form.title"
                    style="width: 100%"
                    placeholder="请输入商品名称"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品分类：" prop="categoryId">
                  <el-cascader
                    v-model="base_form.categoryPath"
                    clearable
                    style="width: calc(100% - 100px)"
                    placeholder="请选择商品分类"
                    :options="category_data"
                    :props="cate_props"
                    @change="categoryChange"
                  >
                    <div slot-scope="scope" @click="clickChange">
                      {{ scope.data.title }}
                    </div>
                  </el-cascader>
                  <el-button size="mini" type="text" @click="add_model = true">
                    【新建分类】
                  </el-button>
                </el-form-item>
                <el-form-item label="副分类：">
                  <div v-for="(item, index) in assist_cate" :key="index">
                    <el-cascader
                      v-model="item.assistCategoryPath"
                      clearable
                      style="width: calc(100% - 120px)"
                      placeholder="请选择商品分类"
                      :options="category_data"
                      :props="cate_props"
                    >
                      <div slot-scope="scope" @click="clickChange">
                        {{ scope.data.title }}
                      </div>
                    </el-cascader>
                    <el-button
                      v-if="index === 0"
                      size="mini"
                      type="text"
                      @click="addAssistCate"
                    >
                      【添加】
                    </el-button>
                    <el-button
                      v-if="assist_cate.length > 1"
                      size="mini"
                      type="text"
                      @click="delAssistCate(index)"
                    >
                      【删除】
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="商品品牌：" prop="brandId">
                  <el-input
                    v-model="base_form.brandName"
                    readonly
                    style="width: calc(100% - 100px)"
                    placeholder="请选择商品品牌"
                  >
                    <i
                      slot="suffix"
                      class="el-input__icon el-icon-search"
                      @click="sel_brand = true"
                    ></i>
                  </el-input>
                  <el-button size="mini" type="text" @click="add_Brand = true">
                    【新建品牌】
                  </el-button>
                </el-form-item>
                <el-form-item
                  v-if="shelfLifeSetUp === 5"
                  label="保质期："
                  prop="expireTime"
                >
                  <el-input-number
                    v-model="base_form.expireTime"
                    style="width: calc(100% - 30px)"
                    :controls="false"
                    :min="1"
                    placeholder="请输入商品保质期"
                  ></el-input-number>
                  天
                </el-form-item>
                <el-form-item label="抄码商品：" prop="describe">
                  <el-switch
                    v-model="base_form.isEq"
                    class="switchStyle"
                    :disabled="isEditSpec === 4"
                    active-text="是"
                    inactive-text="否"
                    active-color="#2153D4"
                    inactive-color="#879BBA"
                    :active-value="5"
                    :inactive-value="4"
                    @change="isEqChange"
                  ></el-switch>
                </el-form-item>
                <el-form-item label="关键词：" prop="tag">
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputVisible"
                    ref="saveTagInput"
                    v-model="inputValue"
                    class="input-new-tag"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  ></el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    style="
                      width: 80px;
                      height: 28px;
                      font-size: 14px;
                      border-radius: 3px;
                      line-height: 3px;
                    "
                    @click="showInput"
                  >
                    + 新增
                  </el-button>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品编码：" prop="code">
                  <el-input
                    v-model="base_form.code"
                    style="width: 100%"
                    disabled
                    placeholder="商品编码自动生成"
                  ></el-input>
                </el-form-item>
                <el-form-item label="货架编码：" prop="code">
                  <el-input
                    v-model="base_form.storage"
                    style="width: 100%"
                    placeholder="货架编码"
                  ></el-input>
                </el-form-item>
                <el-form-item label="禁止销售店铺：">
                  <SelectShop
                    v-model="base_form.noSalesShop"
                    width="530"
                    :multiple="true"
                    :enable="true"
                  />
                </el-form-item>
                <el-form-item label="商品卖点：" prop="describe">
                  <el-input
                    v-model="base_form.describe"
                    style="width: 100%"
                    placeholder="请输入商品卖点"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商户：">
                  <el-select
                    v-if="!base_goods_id"
                    v-model="base_form.merchantId"
                    placeholder="选择商户"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in sel_cities"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <el-input
                    v-else
                    v-model="base_form.merchantName"
                    style="width: 100%"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="detail-tab-main">
            <div class="order_midden_left_text">
              <span class="el-icon-arrow-right"></span>
              <span>商品单位</span>
              <el-button
                size="mini"
                type="text"
                @click="$router.push('/goods/manageG/UnitMeasurement')"
              >
                【单位管理】
              </el-button>
              <el-button size="mini" type="text" @click="getAllUnit">
                【刷新】
              </el-button>
              <span class="desc-span">
                （在商品【采购之后】，基本单位不允许修改，基本单位为最小度量单位）
              </span>
            </div>
            <el-form-item prop="masterUnit">
              <div slot="label">
                <span style="color: #e60000">*</span>
                <span>基本单位</span>
                <el-tooltip
                  effect="dark"
                  content="基本单位与辅助单位之间须有固定的换算关系，例如：1箱牛奶=24盒，【单位关系】为24，基本单位为【盒】，辅助单位为【箱】"
                  placement="top-start"
                >
                  <i class="el-icon-info"></i>
                </el-tooltip>
                ：
              </div>
              <vxe-select
                v-model="base_form.masterUnit.unitId"
                :disabled="isEditSpec === 4"
                placeholder="请选择基本单位"
                @change="masterUnitChange"
              >
                <vxe-option
                  v-for="(itemU, indexU) in unit_options"
                  :key="indexU"
                  :label="itemU.unitName"
                  :disabled="
                    base_form.isEq === 5 &&
                    itemU.unitName !== 'KG' &&
                    itemU.unitName !== '斤'
                  "
                  :value="itemU.id"
                ></vxe-option>
              </vxe-select>
              <div v-if="!spec_table_Data.length" style="display: inline-block">
                <vxe-input
                  v-model="base_form.masterUnit.barCode"
                  style="width: 200px; margin: 0 12px"
                  placeholder="请输入商品条码"
                ></vxe-input>
                <vxe-input
                  v-model="base_form.masterUnit.weight"
                  type="number"
                  style="width: 200px"
                  placeholder="请输入商品重量"
                  @blur="changeWeight"
                >
                  <template #suffix>
                    <span style="color: #2d405e">g</span>
                  </template>
                </vxe-input>
                <span style="margin-left: 24px">默认单位：</span>
                <el-switch
                  v-model="base_form.masterUnit.isDefault"
                  class="switchStyle"
                  active-color="#2153D4"
                  inactive-color="#879BBA"
                  active-text="是"
                  inactive-text="否"
                  :inactive-value="4"
                  :active-value="5"
                  @change="isDefaultChange($event, 'masterUnit')"
                ></el-switch>
              </div>
            </el-form-item>
            <el-form-item prop="branchUnit" label="辅助单位：">
              <div
                v-for="(itemA, indext) in base_form.branchUnit"
                :key="indext"
                :style="{
                  display: !spec_table_Data.length ? 'block' : 'inline-block',
                }"
              >
                <el-tag
                  :closable="isEditSpec === 5 || base_form.isEq === 5"
                  :disable-transitions="false"
                  @close="delFuUnit(itemA, indext)"
                >
                  <span v-if="itemA.isNew === 4">
                    1{{ base_form.masterUnit.unitName }}={{ itemA.conversion
                    }}{{ itemA.unitName }}
                  </span>
                  <span v-else>
                    1{{ itemA.unitName }}={{ itemA.conversion
                    }}{{ base_form.masterUnit.unitName }}
                  </span>
                </el-tag>
                <div
                  v-if="!spec_table_Data.length"
                  style="display: inline-block"
                >
                  <el-input
                    v-model="itemA.barCode"
                    style="width: 200px; margin: 0 10px"
                    placeholder="请输入商品条码"
                  ></el-input>
                  <el-input
                    v-model="itemA.weight"
                    style="width: 200px"
                    placeholder="请输入商品重量"
                  >
                    <el-button slot="append">g</el-button>
                  </el-input>
                  <span style="margin-left: 10px; font-size: 12px">
                    默认单位：
                  </span>
                  <el-switch
                    v-model="itemA.isDefault"
                    class="switchStyle"
                    active-color="#2153D4"
                    inactive-color="#879BBA"
                    active-text="是"
                    inactive-text="否"
                    :inactive-value="4"
                    :active-value="5"
                    @change="isDefaultChange($event, indext)"
                  ></el-switch>
                </div>
              </div>
              <el-button
                v-if="
                  base_form.isEq === 4 ||
                  (base_form.isEq === 5 && base_form.branchUnit.length < 1)
                "
                :disabled="!base_form.masterUnit.unitName"
                type="text"
                @click="addFuUnit"
              >
                <i
                  style="font-size: 14px; margin-right: 10px"
                  class="iconfont icon-xinzeng"
                ></i>
                <span>新增单位</span>
              </el-button>
            </el-form-item>
          </div>
        </el-form>
        <el-form v-show="page_tabs === '2'" label-width="120px" size="small">
          <div class="detail-tab-main">
            <div class="order_midden_left_text">
              <span class="el-icon-arrow-right"></span>
              <span>商品图集</span>
              <span class="desc-span">
                （建议上传尺寸375px*375px，格式：jpg,jpeg,png;
                大小：建议小于1M。）
              </span>
            </div>
            <el-form-item prop="images" label-width="20px">
              <UploadQiniu
                :limit="10"
                :file-list="img_list"
                @uploadSuccess="uploadSuccess"
                @imgSortChange="imgSortChange"
                @handleRemove="uploadRemove"
              />
            </el-form-item>
            <div class="order_midden_left_text">
              <span class="el-icon-arrow-right"></span>
              <span>商品详情</span>
            </div>
            <Tinymce v-model="base_form.description" :height="300" />
          </div>
        </el-form>
        <el-form v-show="page_tabs === '3'" label-width="120px" size="small">
          <div class="detail-tab-main">
            <div class="order_midden_left_text">
              <span class="el-icon-arrow-right"></span>
              <span>商品属性</span>
              <el-button
                size="mini"
                type="text"
                @click="$router.push('/goods/manageG/SpecManage')"
              >
                【属性管理】
              </el-button>
              <el-button size="mini" type="text" @click="SpecManagegetAll">
                【刷新】
              </el-button>
              <span v-if="isEditSpec === 5" class="desc-span">
                （在该商品【采购之前】若不设置商品属性，在该商品【采购之后】，属性不允许重新设置，请谨慎操作！）
              </span>
              <span v-else class="desc-span">
                （请确认当前属性是否有库存，一旦删除该属性无法售卖；新增规格会导致原有库存重置；请谨慎操作！）
              </span>
            </div>
            <div v-if="!sku_list.length">
              <el-button type="primary" @click="addSkuP">添加属性</el-button>
            </div>
            <div v-for="(itemS, indexS) in sku_list" :key="indexS">
              <el-form-item prop="groupSpecId" label="属性名：">
                <el-select
                  v-model="itemS.groupSpecId"
                  style="width: 100%"
                  filterable
                  :disabled="isEditSpec === 4"
                  placeholder="请选择属性"
                  @change="groupSpecIdChange($event, indexS)"
                >
                  <el-option
                    v-for="(itemU, indexU) in spec_data"
                    :key="indexU"
                    :label="itemU.specName"
                    :value="itemU.id"
                  ></el-option>
                </el-select>
                <el-button
                  v-if="isEditSpec === 5"
                  type="text"
                  size="mini"
                  @click="delGroupSpecId(indexS)"
                >
                  删除
                </el-button>
                <el-button
                  v-if="indexS === 0 && isEditSpec === 5"
                  type="text"
                  @click="addSkuP"
                >
                  <i
                    style="font-size: 14px; margin-right: 5px"
                    class="iconfont icon-xinzeng"
                  ></i>
                  添加属性
                </el-button>
              </el-form-item>
              <el-form-item label="属性值：" prop="params">
                <el-tag
                  v-for="(itemC, indexC) in itemS.params"
                  :key="indexC"
                  :closable="isEditSpec === 5"
                  :disable-transitions="false"
                  @close="delSpecVal(indexC, indexS, itemC)"
                >
                  {{ itemC.specName }}
                </el-tag>
                <el-button
                  :disabled="!itemS.groupSpecId"
                  type="text"
                  @click="addSpecVal(indexS)"
                >
                  + 选择属性值
                </el-button>
                <el-input
                  v-if="itemS.self_spec_input"
                  v-model="itemS.self_spec_val"
                  size="small"
                  style="width: 200px"
                  placeholder="请输入内容"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-check"
                    @click="selfSpecConfirm(indexS)"
                  ></el-button>
                </el-input>
                <el-button
                  v-else
                  :disabled="!itemS.groupSpecId"
                  type="text"
                  @click="itemS.self_spec_input = true"
                >
                  + 新增属性值
                </el-button>
              </el-form-item>
            </div>
            <!--              规格明细-->
            <div v-show="spec_table_Data.length > 0">
              <p class="order_midden_left_text">
                <span class="el-icon-arrow-right"></span>
                <span>规格明细</span>
              </p>
              <el-table :data="spec_table_Data">
                <el-table-column width="50" type="index"></el-table-column>
                <el-table-column
                  v-for="(item, index) in sku_list"
                  :key="index"
                  prop="specName"
                  min-width="100px"
                  :label="item.groupSpecName"
                >
                  <template slot-scope="scope">
                    {{
                      scope.row.specName.indexOf("_") > -1
                        ? scope.row.specName.split("_")[index] || ""
                        : scope.row.specName
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="specImage"
                  label="规格图片"
                  min-width="140px"
                >
                  <template slot-scope="scope">
                    <UploadQiniu
                      :width="50"
                      is-btn="picture"
                      :file-list="
                        scope.row.specImage.url ? [scope.row.specImage] : []
                      "
                      @uploadSuccess="uploadSpecSuccess($event, scope.$index)"
                    ></UploadQiniu>
                  </template>
                </el-table-column>
                <el-table-column label="商品条码" min-width="200px">
                  <template slot-scope="scope">
                    <div
                      v-for="(itemU, indexU) in scope.row.barCode"
                      :key="indexU"
                      style="padding-bottom: 5px"
                    >
                      <span>{{ itemU.unitName }}：</span>
                      <el-input
                        v-model="itemU.barCode"
                        style="width: 160px"
                        size="small"
                        placeholder="请输入商品条码"
                      ></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="商品重量" min-width="200px">
                  <template slot-scope="scope">
                    <div
                      v-for="(itemU, indexU) in scope.row.barCode"
                      :key="indexU"
                      style="padding-bottom: 5px"
                    >
                      <span>{{ itemU.unitName }}：</span>
                      <el-input
                        v-model="itemU.weight"
                        style="width: 160px"
                        size="small"
                        placeholder="请输入商品重量 (g)"
                      >
                        <el-button slot="append">g</el-button>
                      </el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="默认属性" min-width="140px">
                  <template slot-scope="scope">
                    <div
                      v-for="(itemU, indexU) in scope.row.barCode"
                      :key="indexU"
                      style="padding-bottom: 5px"
                    >
                      <span>{{ itemU.unitName }}：</span>
                      <el-switch
                        v-model="itemU.isDefault"
                        active-color="#36B365"
                        inactive-color="#ff4949"
                        active-text="是"
                        inactive-text="否"
                        :inactive-value="4"
                        :active-value="5"
                        @change="isDefaultChange($event, indexU, scope.$index)"
                      ></el-switch>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="!!base_goods_id"
                  prop="inventory"
                  min-width="120px"
                  label="库存"
                >
                  <template slot-scope="scope">
                    {{
                      scope.row.isEditSpec === 5
                        ? "无记录"
                        : scope.row.inventory
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="80px">
                  <template slot-scope="scope">
                    <el-button
                      :disabled="scope.row.isEditSpec === 4"
                      type="text"
                      @click="specDetailDel(scope.row, scope.$index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form>
      </div>
    </div>
    <el-dialog
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :title="edit_assist_model ? '修改辅助单位' : '新增辅助单位'"
      :visible.sync="assist_model"
      width="40%"
    >
      <el-form
        style="text-align: center"
        :model="assist_form"
        size="small"
        inline
      >
        <div v-if="isNew === 4">
          <el-form-item prop="conversion">
            1
            {{ base_form.masterUnit.unitName }}
            =
          </el-form-item>
          <el-form-item prop="unitName">
            <el-input-number
              v-model="assist_form.conversion"
              :controls="false"
            ></el-input-number>
            <el-select
              v-model="assist_form.unitId"
              placeholder="请选择辅助单位"
              @change="branchUnitChange"
            >
              <el-option
                v-for="(item, index) in unit_options"
                :key="index"
                :label="item.unitName"
                :value="item.id"
                :disabled="item.unitName === base_form.masterUnit.unitName"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item prop="conversion">
            1
            <el-select
              v-model="assist_form.unitId"
              placeholder="请选择辅助单位"
              @change="branchUnitChange"
            >
              <template v-for="(item, index) in unit_options">
                <el-option
                  :key="index"
                  :label="item.unitName"
                  :value="item.id"
                  :disabled="item.unitName === base_form.masterUnit.unitName"
                ></el-option>
              </template>
            </el-select>
            =
          </el-form-item>
          <el-form-item prop="unitName">
            <el-input-number
              v-model="assist_form.conversion"
              :controls="false"
            ></el-input-number>
            {{ base_form.masterUnit.unitName }}
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assist_model = false">取 消</el-button>
        <el-button type="primary" @click="subAssist">确 定</el-button>
      </span>
    </el-dialog>
    <!--   属性值 -->
    <el-dialog title="属性值" :visible.sync="spec_model" width="40%">
      <el-checkbox
        v-model="spec_check_all"
        :indeterminate="is_indeterminate_spec"
        @change="checkAllSpecChange"
      >
        全选
      </el-checkbox>
      <div style="margin: 15px 0"></div>
      <el-checkbox-group v-model="spec_item_check" @change="specItemChange">
        <el-checkbox
          v-for="(item, index) in spec_data_child"
          :key="index"
          :label="item.id"
        >
          {{ item.specName }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="spec_model = false">取 消</el-button>
        <el-button type="primary" @click="selSpecVal">确 定</el-button>
      </span>
    </el-dialog>
    <BrandSelModel
      v-if="sel_brand"
      :is-check="false"
      :is-show-add="true"
      :dialog-visible="sel_brand"
      :enable="true"
      @close="sel_brand = false"
      @confirm="brandConfirm"
    />
    <!-----------------    添加分类 ----------->
    <AddCate
      v-if="add_model"
      :dialog-title="dialogTitle"
      :is-show="add_model"
      :pid-path="pid_arr"
      @confirm="subCategory"
      @cancel="modelClose"
    />
    <!--   新建品牌-->
    <el-drawer
      class="edit-drawer"
      size="50%"
      :visible.sync="add_Brand"
      direction="rtl"
    >
      <AddBrand v-if="add_Brand" @submitBrand="submitBrand" />
    </el-drawer>
  </ContainerTit>
</template>

<script>
  import GoodsCategory from "@/component/common/GoodsCategory.vue";
  import BrandSelModel from "@/component/goods/BrandSelModel.vue";
  import Tinymce from "@/component/Tinymce";
  import UploadQiniu from "@/component/common/UploadQiniu.vue";
  // 新增分类
  import AddCate from "@/component/goods/AddCate.vue";
  import AddBrand from "./AddBrand";
  import SelectShop from "@/component/goods/SelectShop.vue";
  import {
    getAllUnit,
    defineSpec,
    SpecManagegetAll,
    getGoodsBasicInfoById,
    editGoodsBasic,
    addGoodsBasic,
    getAllCategoryPost,
  } from "@/api/goods";
  import { addPauseSave, delPauseSave, getPauseSave } from "@/api/common";
  import { getAllMerchantList } from "@/api/Merchants";
  export default {
    name: "AddBaseData",
    components: {
      // GoodsCategory,
      BrandSelModel,
      Tinymce,
      UploadQiniu,
      AddCate,
      AddBrand,
      SelectShop,
    },
    data() {
      const validateUnit = (rule, value, callback) => {
        if (value.unitName === "") {
          callback(new Error("请设置基本单位"));
        } else {
          callback();
        }
      };
      return {
        // 计量单位
        self_spec_val: "", // 自定义属性值输入框
        spec_name_index: 0, // 属性名index
        self_spec_input: false, // 显示自定义属性值输入框
        spec_model: false, // 选择属性值弹窗
        spec_item_check: [], // 属性值弹窗单选value
        is_indeterminate_spec: false, // 批量选择属性值 全选选择框状态
        spec_check_all: false, // 属性值 全选选择框value
        spec_data: [], // 属性列表
        spec_data_child: [], // 属性值列表
        spec_table_Data: [], // 规格明细
        sku_list: [
          // 商品属性列表
          {
            spec_data_child: [],
            groupSpecId: "",
            self_spec_val: "",
            self_spec_input: false,
            groupSpecName: "",
            params: [],
          },
        ],
        add_model: false, // 新建分类
        dialogTitle: "新建分类",
        pid_arr: [],
        add_Brand: false, // 新增品牌
        pageName: "", // 暂存数据参数
        loading: false,
        img_list: [],
        // 关键词
        dynamicTags: [],
        inputVisible: false,
        inputValue: "",
        // 关键词 END
        assist_model: false,
        edit_assist_model: false,
        assist_index: 0,
        unit_options: [],
        // 计量单位弹窗
        assist_form: {
          unitName: "",
          isMaster: 4,
          isDefault: 4,
          weight: "",
          unitId: "",
          barCode: "",
          conversion: "",
        },
        sel_brand: false, // 打开品牌选择弹窗
        sel_shop: false, // 打开店铺选择弹窗
        master_unit_name: "",
        base_form: {
          //  基本信息
          specType: 1, // 是否多规格
          delUnitIds: [], // 辅助单位删除delUnitIds (unitId)
          delSpecSkuIds: [], // 属性删除delSpecSkuIds（这个用id）
          branchUnit: [],
          brandName: "",
          categoryPath: [], // 分类选择
          assistCategoryPath: [], //副分类
          noSalesShop: [],
          unitData: [],
          isEq: 4, //是否是抄码商品
          masterUnit: {
            isDefault: 5,
            isMaster: 5,
            weight: "",
            unitName: "",
            unitId: "",
            barCode: "",
          },
          describe: "",
          storage: "",
          title: "",
          code: "",
          barCode: "", // 商品条码
          categoryId: "",
          assistCategoryId: "",
          expireTime: "",
          brandId: "",
          tag: "",
          description: "",
          salesShop: "",
          images: [],
          merchantId: "", //商户ID
        },
        base_rules: {
          // 基本信息验证
          title: [
            { required: true, message: "请输入商品名称", trigger: "blur" },
          ],
          categoryId: [
            { required: true, message: "请选择商品分类", trigger: "change" },
          ],
          expireTime: [
            { required: true, message: "请输入商品保质期", trigger: "blur" },
          ],
          masterUnit: [{ validator: validateUnit, trigger: "change" }],
        },

        images_rules: {
          images: [
            {
              type: "array",
              required: true,
              message: "请上传商品图片",
              trigger: "change",
            },
          ],
        },
        base_goods_id: 0,
        isEditSpec: 5, // 5 表示此商品从未采购过，允许用户随意编辑单位和属性；4 表示商品已经采购过，隐藏添加属性按钮，避免skuid重组
        isNew: 5, // 5 标示这是一个最近新增的商品，基本单位为最小单位，4标示这是之前的老数据，基本单位为最大单位3
        sel_merchant: false,
        sel_cities: [],
        category_data: [], //商品分类列表
        cate_props: {
          label: "title",
          value: "id",
          checkStrictly: true,
        },
        assist_cate: [
          {
            assistCategoryPath: [],
          },
        ],
        page_tabs: "1",
        step_active: 1,
      };
    },
    async created() {
      // this.getAllGoodsSupport();
      // 商品分类列表
      await this.getAllCategoryPost();
      this.pageName = this.$route.name;

      // 商户管理
      await this.getAllMerchantList();
      // 属性管理
      await this.SpecManagegetAll();
      await this.getAllUnit();
      if (this.$route.params.id) {
        this.base_goods_id = this.$route.params.id;
        await this.getGoodsBasicInfoById();
      } else {
        // 获取暂存信息
        await this.getPauseSave();
      }
    },
    async activated() {
      if (this.$_isInit()) return;
      this.pageName = this.$route.name;
      this.step_active = 1;
      this.page_tabs = "1";
      if (this.$route.params.id) {
        this.base_goods_id = this.$route.params.id;
        await this.getGoodsBasicInfoById();
      } else {
        // 获取暂存信息
        await this.getPauseSave();
      }
    },
    methods: {
      // 默认单位change
      isDefaultChange(val, index, sIndex) {
        // 多规格数据
        if (this.spec_table_Data.length > 0) {
          if (val === 5) {
            const target = this.$_common.deepClone(this.spec_table_Data);
            target.forEach((item, indexS) => {
              item.barCode.forEach((itemB, indexB) => {
                if (indexS !== sIndex) {
                  itemB.isDefault = 4;
                } else {
                  if (indexB !== index) {
                    itemB.isDefault = 4;
                  }
                }
              });
            });
            this.spec_table_Data = target;
          }
        } else {
          if (val === 5) {
            if (index === "masterUnit") {
              this.base_form.branchUnit.forEach((item) => {
                item.isDefault = 4;
              });
            } else {
              this.base_form.masterUnit.isDefault = 4;
              this.base_form.branchUnit.forEach((item, indexU) => {
                if (indexU !== index) {
                  item.isDefault = 4;
                }
              });
            }
          }
        }
      },
      // 请求基本单位数据
      async getAllUnit() {
        const { data } = await getAllUnit({
          page: 1,
          pageSize: 99,
          source: 4,
        });

        this.unit_options = data;
      },
      modelClose() {
        this.add_model = false;
      },
      // 打开新增弹窗
      openModel(title, row) {
        this.add_model = true;
        this.dialogTitle = title;
        if (title === "新建子分类") {
          let link = row.link
            ? row.link.split(",").map((item) => {
                return parseInt(item);
              })
            : [];
          link.push(row.id);
          this.pid_arr = link;
        }
      },
      // 新增/编辑分类
      async subCategory() {
        await this.getAllCategoryPost();
      },
      // 新建品牌
      submitBrand() {
        this.add_Brand = false;
      },
      // 添加暂存
      async AddTem() {
        const params = {
          ...this.base_form,
          specGroup: this.sku_list,
          specMultiple: this.spec_table_Data,
          tag: this.dynamicTags,
          assist_cate: this.assist_cate,
        };
        const data = await addPauseSave({
          key: this.pageName,
          data: params,
        });
        this.$message({
          type: "success",
          message: "暂存成功",
        });
        this.$closeCurrentGoEdit("/goods/manageG/BaseDataList");
      },
      // 删除暂存信息
      async delPauseSave(type) {
        const data = delPauseSave({
          key: this.pageName,
        });

        if (type) {
          this.$message({
            type: "success",
            message: "清除暂存成功",
          });
          this.$closeCurrentGoEdit("/goods/manageG/AddBaseData");
        }
      },
      // 获取暂存信息
      async getPauseSave() {
        const { data } = await getPauseSave({
          key: this.pageName,
        });

        if (JSON.stringify(data) === "{}") return;
        this.base_form = {
          ...data,
          categoryPath: Array.isArray(data.categoryPath)
            ? data.categoryPath
            : [],
        };
        this.assist_cate = data.assist_cate || [{ assistCategoryPath: [] }];
        this.sku_list = data.specGroup || [];
        this.spec_table_Data = data.specMultiple || [];
        this.dynamicTags = data.tag || [];
        if (data.images) {
          this.img_list = data.images.map((item) => {
            return {
              name: "",
              url: item,
            };
          });
        }
      },

      // 规格明细删除
      specDetailDel(row, index) {
        if (
          row.specGroupHash &&
          this.base_form.delSpecSkuIds.indexOf(row.specGroupHash) === -1
        ) {
          this.base_form.delSpecSkuIds.push(row.specGroupHash);
        }
        this.spec_table_Data.splice(index, 1);
        const specNameArr = row.specName.indexOf("_")
          ? row.specName.split("_")
          : row.specName;
        // console.log('specNameArr', row.specName)
        // console.log('this.spec_table_Data', this.spec_table_Data)
        let isFalseVal = "";
        for (let i in specNameArr) {
          let itemS = specNameArr[i];
          // console.log(itemS)
          // console.log(this.spec_table_Data.find(item => item.specName.indexOf(itemS) > -1))
          if (
            !this.spec_table_Data.find(
              (item) => item.specName.indexOf(itemS) > -1
            )
          ) {
            isFalseVal = itemS;
            break;
          }
        }
        // console.log('isStay,', isFalseVal)
        // console.log(this.sku_list)
        if (isFalseVal) {
          this.sku_list.forEach((item) => {
            const indexP = item.params.findIndex(
              (itemP) => itemP.specName === isFalseVal
            );
            if (indexP > -1) {
              item.params.splice(indexP, 1);
            }
          });
        }
      },
      // ddel(val) {
      //   this.from.categoryPath = val;
      // },
      // 规格图片
      uploadSpecSuccess(val, index) {
        let target = this.$_common.deepClone(this.spec_table_Data);
        target[index].specImage = {
          name: "",
          url: val,
        };
        this.spec_table_Data = target;
      },
      // 添加规格项目
      addSkuP() {
        if (this.isEditSpec === 5) {
          this.sku_list.push({
            spec_data_child: [],
            self_spec_input: false,
            self_spec_val: "",
            groupSpecId: "",
            groupSpecName: "",
            params: [],
          });
        } else {
          this.$confirm(
            "新增规格会导致原有库存重置,请谨慎操作! 是否继续?",
            "提示",
            {
              confirmButtonText: "继续新增",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.sku_list.push({
                spec_data_child: [],
                self_spec_input: false,
                self_spec_val: "",
                groupSpecId: "",
                groupSpecName: "",
                params: [],
              });
            })
            .catch(() => {});
        }
      },
      // 规格明切换
      groupSpecIdChange(val, indexS) {
        let target = this.$_common.deepClone(this.sku_list);
        const specDataItem = this.spec_data.find((item) => item.id === val);
        const isHave = target.find(
          (item) => item.groupSpecName === specDataItem.specName
        );
        if (isHave) {
          target[indexS].groupSpecId = "";
          this.sku_list = target;
          this.$message.warning(`属性:【${specDataItem.specName}】已存在`);
          return;
        }
        target[indexS].groupSpecName = specDataItem.specName;
        target[indexS].spec_data_child = specDataItem.child || [];
        target[indexS].params = [];
        this.sku_list = target;
        // 重排规格组合
        // this.specGroupRest()
        // console.log(this.sku_list)
        // console.log(this.spec_table_Data)
      },
      // 重排规格组合
      specGroupRest() {
        // 编辑页面存储详情接口返回规格组合id
        this.spec_table_Data.forEach((item) => {
          if (
            item.specGroupHash &&
            this.base_form.delSpecSkuIds.indexOf(item.specGroupHash) === -1
          ) {
            this.base_form.delSpecSkuIds.push(item.specGroupHash);
          }
        });
        // 备份一份规格明细，用来填充重排规格组之前的数据
        const cloneSpecGroup = this.$_common.deepClone(this.spec_table_Data);
        const skuArr = this.sku_list.map((item) => {
          item.params = item.params.map((itemP) => {
            return {
              ...itemP,
              groupSpecName: item.groupSpecName,
            };
          });
          return item.params;
        });
        // console.log('skuArr::', skuArr)
        this.spec_table_Data = this.doExchange(skuArr);
        // console.log(this.spec_table_Data)

        this.spec_table_Data.forEach((item) => {
          const index = cloneSpecGroup.findIndex(
            (itemC) => itemC.id === item.id
          );
          if (index > -1) {
            item.barCode = cloneSpecGroup[index].barCode;
            item.specImage = cloneSpecGroup[index].specImage;
            item.inventory = cloneSpecGroup[index].inventory;
            item.isEditSpec = cloneSpecGroup[index].isEditSpec || 5;
          }
        });
      },
      // 规格组合
      doExchange(doubleArrays) {
        const len = doubleArrays.length;
        let unitData = this.$_common.deepClone(this.base_form.branchUnit);
        unitData.unshift(this.base_form.masterUnit);
        const barCodeArr = unitData.map((item) => {
          return {
            ...item,
            barCode: "",
            weight: "",
            isDefault: 4,
          };
        });
        if (len >= 2) {
          const len1 = doubleArrays[0].length;
          const len2 = doubleArrays[1].length;
          const newlen = len1 * len2;
          const temp = new Array(newlen);
          let index = 0;
          for (let i = 0; i < len1; i++) {
            for (let j = 0; j < len2; j++) {
              temp[index] = {
                groupSpecId:
                  doubleArrays[0][i].groupSpecId +
                  "_" +
                  doubleArrays[1][j].groupSpecId,
                groupSpecName:
                  doubleArrays[0][i].groupSpecName +
                  "_" +
                  doubleArrays[1][j].groupSpecName,
                id: doubleArrays[0][i].id + "_" + doubleArrays[1][j].id,
                specName:
                  doubleArrays[0][i].specName +
                  "_" +
                  doubleArrays[1][j].specName,
                specImage: {
                  name: "",
                  url: "",
                },
                barCode: this.$_common.deepClone(barCodeArr),
              };
              index++;
            }
          }
          let newArray = new Array(len - 1);
          newArray[0] = temp;
          if (len > 2) {
            let _count = 1;
            for (let i = 2; i < len; i++) {
              newArray[_count] = doubleArrays[i];
              _count++;
            }
          }
          return this.doExchange(newArray);
        } else if (len > 0) {
          return doubleArrays[0].map((item) => {
            return {
              ...item,
              barCode: this.$_common.deepClone(barCodeArr),
              specImage: {
                name: "",
                url: "",
              },
            };
          });
        } else {
          return [];
        }
      },
      // 自定义属性值输入框确定  添加自定义属性
      async selfSpecConfirm(index) {
        const target = this.$_common.deepClone(this.sku_list);

        if (!target[index].self_spec_val) {
          target[index].self_spec_input = false;
          this.sku_list = target;
          return;
        }
        // 检查当前属性值是否已被选择
        const isHave = target[index].params.find(
          (item) => item.specName === target[index].self_spec_val
        );
        if (isHave) {
          this.$message.warning(
            `属性值:【${target[index].self_spec_val}】已存在`
          );
          target[index].self_spec_val = "";
          target[index].self_spec_input = false;
          this.sku_list = target;
          return;
        }
        // 属性值未被选择 做接口请求
        const { data } = await defineSpec({
          specName: target[index].self_spec_val,
          pid: target[index].groupSpecId,
          hidden: 4,
        });
        target[index].self_spec_input = false;
        target[index].params.push({
          specName: data.specName,
          id: data.id,
          groupSpecId: target[index].groupSpecId,
        });
        target[index].self_spec_val = "";
        this.sku_list = target;
        // 重排规格组合
        this.specGroupRest();
      },
      // 新增规格值
      addSpecVal(indexS) {
        this.spec_model = true;
        this.spec_data_child = this.sku_list[indexS].spec_data_child;
        this.spec_name_index = indexS;
        this.spec_item_check = this.sku_list[indexS].params.map(
          (item) => item.id
        );
        // 使用属性值单选方法，为了设置全选选择框状态
        this.specItemChange(this.spec_item_check);
      },
      // 选择属性值
      selSpecVal() {
        const target = this.$_common.deepClone(this.sku_list);
        const specval = this.spec_data_child
          .filter((item) => {
            return (
              this.spec_item_check.findIndex((itemS) => itemS === item.id) > -1
            );
          })
          .map((item) => {
            return {
              specName: item.specName,
              id: item.id,
              groupSpecId: item.pid,
            };
          });
        target[this.spec_name_index].params = this.$_common.unique(
          target[this.spec_name_index].params.concat(specval),
          ["id"]
        );
        this.sku_list = target;
        this.spec_model = false;
        // 重排规格组合
        this.specGroupRest();
      },
      // 属性值全选
      checkAllSpecChange(val) {
        this.is_indeterminate_spec = false;
        if (val) {
          this.spec_item_check = this.spec_data_child.map((item) => {
            return item.id;
          });
        } else {
          this.spec_item_check = [];
        }
      },
      // 属性值单选
      specItemChange(val) {
        let checkedCount = val.length;
        this.spec_check_all = checkedCount === this.spec_data_child.length;
        this.is_indeterminate_spec =
          checkedCount > 0 && checkedCount < this.spec_data_child.length;
      },
      // 删除规格值
      delSpecVal(indexC, indexS, itemC) {
        this.$confirm("确定要删除该规格值吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          if (this.base_goods_id) {
            this.base_form.delSpecSkuIds = this.spec_table_Data
              .filter((item) => item.specName.indexOf(itemC.specName) > -1)
              .map((itemM) => {
                return itemM.specGroupHash;
              });
          }
          this.spec_table_Data = this.spec_table_Data.filter(
            (item) => item.specName.indexOf(itemC.specName) === -1
          );
          const target = this.$_common.deepClone(this.sku_list);
          target[indexS].params.splice(indexC, 1);
          this.sku_list = target;
        });
      },
      // 删除规格组
      delGroupSpecId(indexS) {
        this.$confirm("确定要删除该规格组吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          this.sku_list.splice(indexS, 1);
          // 重排规格组合
          this.specGroupRest();
        });
      },

      // 获取属性列表
      async SpecManagegetAll() {
        const { data, pageTotal } = await SpecManagegetAll({
          page: 1,
          pageSize: 100,
        });

        this.spec_data = data.filter((item) => item.specName !== "计量单位");
        // this.unit_options = data.find(item => item.specName === '计量单位').child
      },
      // 选择图片
      uploadSuccess(val, res, file, fileList) {
        const imgArr = fileList.map((item) => {
          return item.content;
        });
        if (this.base_form.images.length) {
          this.base_form.images = this.base_form.images.concat(imgArr);
        } else {
          this.base_form.images = imgArr;
        }
        this.img_list = this.base_form.images.map((item) => {
          return {
            name: "",
            content: item,
          };
        });
        if (this.img_list.length > 10) {
          this.$message.warning("图片最多只能选择十张");
          this.img_list = this.img_list.slice(0, 10);
        }
      },
      // 图片拖拽排序
      imgSortChange(list) {
        this.base_form.images = list.map((item) => {
          return item.content;
        });
      },
      uploadRemove(file, fileList) {
        this.base_form.images = fileList.map((item) => {
          return item.content;
        });
      },
      // 关键词删除
      handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },
      // 关键词显示输入框
      showInput() {
        this.inputVisible = true;
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 关键词显示输入确定
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = "";
      },
      // 关键词END
      // 设置计量单位
      // 删除辅助单位
      delFuUnit(row, it) {
        if (
          row.unitId &&
          this.base_form.delUnitIds.indexOf(row.unitId) === -1
        ) {
          this.base_form.delUnitIds.push(row.unitId);
        }
        this.spec_table_Data = this.spec_table_Data.map((item) => {
          return {
            ...item,
            barCode: item.barCode.filter((item) => item.unitId !== row.unitId),
          };
        });
        this.base_form.branchUnit.splice(it, 1);
      },
      // 新增辅助单位
      addFuUnit() {
        this.assist_model = true;
        this.edit_assist_model = false;
        this.assist_form = {
          unitName: "",
          isMaster: 4,
          unitId: "",
          conversion: "",
        };
      },
      // 修改附单位
      EditFuUnit(it) {
        this.assist_model = true;
        this.edit_assist_model = true;
        this.assist_form = this.base_form.branchUnit[it];
        this.assist_index = it;
      },
      // 弹窗提交
      subAssist() {
        if (!this.assist_form.conversion) {
          this.$message.warning("请输入单位件换算关系");
          return;
        }
        if (!this.assist_form.unitName) {
          this.$message.warning("请选择辅助单位");
          return;
        }
        if (!this.edit_assist_model) {
          this.assist_form.weight =
            this.base_form.masterUnit.weight * this.assist_form.conversion;
          this.base_form.branchUnit.push(this.assist_form);
        } else {
          this.base_form.branchUnit[this.assist_index] = this.assist_form;
        }
        this.assist_model = false;
        this.spec_table_Data = this.spec_table_Data.map((item) => {
          item.barCode.push(this.$_common.deepClone(this.assist_form));
          return {
            ...item,
          };
        });
      },
      changeWeight() {
        const target = this.$_common.deepClone(this.base_form.branchUnit);
        target.forEach((item) => {
          item.weight = this.base_form.masterUnit.weight * item.conversion;
        });
        this.base_form.branchUnit = target;
      },
      // 基本单位切换
      masterUnitChange({ value, $event }) {
        // 编辑页面把删除 的单位ID存储下来
        if (!!this.base_goods_id) {
          const unitData = this.$_common.deepClone(this.base_form.unitData);

          this.base_form.delUnitIds = unitData.map((item) => item.unitId);
          if (this.base_form.specType === 1) {
            const specMultiple = this.$_common.deepClone(
              this.base_form.specMultiple
            );
            this.base_form.delSpecSkuIds = specMultiple.map((item) => item.id);
          }

          //把所有的单位删除，重新设置一个新的主单位
          if (this.base_form.masterUnit.id) {
            delete this.base_form.masterUnit.id;
          }
        }

        const val = value;
        this.base_form.masterUnit.unitName = this.unit_options.find(
          (item) => item.id === val
        ).unitName;
        // 重置辅助单位
        this.base_form.branchUnit = [];
        this.spec_table_Data = this.spec_table_Data.map((item) => {
          const index = item.barCode.findIndex((itemF) => itemF.isMaster === 5);
          const barObj = {
            ...this.$_common.deepClone(this.base_form.masterUnit),
            barCode: item.barCode[index].barCode || "",
          };
          this.$set(item.barCode, index, barObj);
          return item;
        });
      },
      // 辅助单位切换
      branchUnitChange(val) {
        this.assist_form.unitName = this.unit_options.find(
          (item) => item.id === val
        ).unitName;
      },
      // 获取详情
      async getGoodsBasicInfoById() {
        const { data } = await getGoodsBasicInfoById(this.base_goods_id);

        this.isEditSpec = data.isEditSpec;
        const unitData = this.$_common.deepClone(data.unitData);
        const masterUnit = unitData.find((item) => item.isMaster === 5) || {};
        const branchUnit = unitData.filter((item) => item.isMaster === 4);
        this.isNew = masterUnit.isNew || 4;
        this.base_form = {
          ...data,
          noSalesShop: data.noSalesShop
            ? data.noSalesShop.split(",").map((item) => parseInt(item))
            : [],
          masterUnit: masterUnit,
          delUnitIds: [],
          delSpecSkuIds: [],
          specType: data.specType,
          branchUnit: branchUnit,
          categoryPath: data.categoryPath
            ? data.categoryPath.split(",").map((item) => {
                return parseInt(item);
              })
            : [],
          assistCategoryPath: data.assistCategoryPath || [],
        };
        if (data.assistCategoryPath && data.assistCategoryPath.length) {
          this.assist_cate = data.assistCategoryPath.map((item) => {
            return {
              assistCategoryPath: item.split(",").map((iteme) => {
                return parseInt(iteme);
              }),
            };
          });
        } else {
          this.assist_cate = [
            {
              assistCategoryPath: [],
            },
          ];
        }

        this.img_list = data.images.map((item) => {
          return {
            name: "",
            url: item,
          };
        });
        this.dynamicTags = data.tag ? data.tag.split(",") : [];
        this.base_form.brandName = data.brandTitle;
        // 多规格数据
        if (parseInt(this.base_form.specType) === 2) {
          this.sku_list = data.specGroup.map((item) => {
            const specData = this.spec_data.find(
              (itemF) => itemF.id === item.groupSpec.specId
            );
            return {
              spec_data_child: specData ? specData.child : [],
              groupSpecId: item.groupSpec.specId,
              groupSpecName: item.groupSpec.specName,
              self_spec_val: "",
              self_spec_input: false,
              params: item.params.map((itemC) => {
                return {
                  id: itemC.specValueId,
                  specName: itemC.specValueName,
                  groupSpecId: item.groupSpec.specId,
                };
              }),
            };
          });
          this.spec_table_Data = data.specMultiple.map((item) => {
            let barCodeA = [];
            for (let b in item.barCode) {
              let unitB = data.unitData.find(
                (itemF) => parseInt(itemF.unitId) === parseInt(b)
              );
              if (unitB) {
                barCodeA.push({
                  ...unitB,
                  barCode: item.barCode[b],
                  weight: item.weight[b],
                  isDefault: item.isDefault[b],
                });
              }
            }
            return {
              barCode: barCodeA,
              isEditSpec: item.isEditSpec,
              inventory: item.inventory - 0,
              specGroupHash: item.specGroupHash,
              id_D: item.id,
              unitId: item.unitId,
              specName: item.specGroup
                .map((itemP) => {
                  return itemP.specValueName;
                })
                .join("_"),
              id: item.specGroup
                .map((itemP) => {
                  return itemP.specValueId;
                })
                .join("_"),
              groupSpecId: item.specGroup
                .map((itemP) => {
                  return itemP.specId;
                })
                .join("_"),
              groupSpecName: item.specGroup
                .map((itemP) => {
                  return itemP.specName;
                })
                .join("_"),
              specImage: {
                name: "",
                url: item.specImage,
              },
            };
          });
        }
      },
      // 发布商品
      async submitGoods() {
        if (!this.base_form.title.trim()) {
          this.$message.warning("商品名称不能为空");
          return;
        }
        if (!this.base_form.categoryPath.length) {
          this.$message.warning("商品分类不能为空");
          return;
        }
        if (!this.base_form.masterUnit.unitId) {
          this.$message.warning("请选择基本单位");
          return;
        }
        this.$refs["base_form"].validate(async (valid) => {
          if (valid) {
            let specGroup = [];
            let specMultiple = [];

            if (!this.base_form.images.length) {
              this.$message.warning("请上传商品图片");
              return;
            }
            if (this.base_form.masterUnit.weight < 0) {
              this.$message.warning("商品重量不能为负数");
              return;
            }
            if (this.spec_table_Data.length > 0) {
              // 多规格
              this.base_form.specType = 2;
              specGroup = this.sku_list.map((item) => {
                return {
                  groupSpec: {
                    specName: item.groupSpecName,
                    specId: item.groupSpecId,
                  },
                  params: item.params.map((item) => {
                    return {
                      specValueId: item.id,
                      specValueName: item.specName,
                    };
                  }),
                };
              });
              specMultiple = this.spec_table_Data.map((item, index) => {
                let specVal = []; // 属性id
                let specId = []; // 属性组id
                let specName = []; // 属性组名
                let specValueName = []; // 属性名
                if ((item.id + "").indexOf("_") > -1) {
                  specVal = item.id.split("_");
                  specId = item.groupSpecId.split("_");
                  specValueName = item.specName.split("_");
                  specName = item.groupSpecName.split("_");
                } else {
                  specVal = [item.id];
                  specId = [item.groupSpecId];
                  specName = [item.groupSpecName];
                  specValueName = [item.specName];
                }
                // 条码
                let barCodeO = {};
                let isDefaultO = {};
                let weightO = {};
                item.barCode.forEach((itemB) => {
                  barCodeO[itemB.unitId] = itemB.barCode;
                  isDefaultO[itemB.unitId] = itemB.isDefault;
                  weightO[itemB.unitId] = itemB.weight;
                });
                let returnParams = {
                  specImage: item.specImage.url,
                  specGroup: specVal.map((itemV, indexV) => {
                    return {
                      specId: specId[indexV],
                      specName: specName[indexV],
                      specValueName: specValueName[indexV],
                      specValueId: itemV,
                    };
                  }),
                  barCode: barCodeO,
                  isDefault: isDefaultO,
                  weight: weightO,
                };
                if (this.$route.params.id) {
                  returnParams.specGroupHash = item.specGroupHash;
                  returnParams.id = item.id_D;
                }
                return returnParams;
              });
            } else {
              this.base_form.specType = 1;
            }
            let unitDataD = this.$_common.deepClone(this.base_form.branchUnit);
            unitDataD.unshift(this.base_form.masterUnit);
            const unitDataA = unitDataD.map((item) => {
              if (this.base_form.specType === 2) {
                item.barCode = "";
                item.isDefault = 4;
                item.weight = "";
              }
              if (
                this.base_form.delSpecSkuIds.indexOf(item.specGroupHash) !==
                  -1 &&
                this.base_form.specType === 1
              ) {
                delete item.id;
              }
              return item;
            });
            // 副分类数据组装
            let assistCategoryPath = [];
            let assistCategoryId = [];
            // 过滤只有选择分类的数据
            const assistCate = this.assist_cate.filter(
              (item) => !!item.assistCategoryPath.length
            );
            assistCate.forEach((item) => {
              assistCategoryPath.push(item.assistCategoryPath.join(","));
              assistCategoryId.push(
                item.assistCategoryPath[item.assistCategoryPath.length - 1]
              );
            });
            const params = {
              merchantId: this.base_form.merchantId,
              categoryPath: this.base_form.categoryPath.join(","),
              assistCategoryPath: assistCategoryPath,
              categoryId: this.base_form.categoryId,
              assistCategoryId: assistCategoryId.join(","),
              title: this.base_form.title,
              storage: this.base_form.storage,
              delUnitIds: this.base_form.delUnitIds,
              delSpecSkuIds: this.base_form.delSpecSkuIds,
              specType: this.base_form.specType,
              specGroup: specGroup,
              specMultiple: specMultiple,
              unitData: unitDataA,
              describe: this.base_form.describe,
              code: this.base_form.code,
              barCode: this.base_form.barCode,
              expireTime: this.base_form.expireTime,
              isEq: this.base_form.isEq,
              brandId: this.base_form.brandId,
              tag: this.dynamicTags.join(","),
              description: this.base_form.description,
              noSalesShop: this.base_form.noSalesShop.join(","),
              images: this.base_form.images,
            };
            this.loading = true;
            let target = {};
            try {
              if (this.$route.params.id) {
                target = await editGoodsBasic(this.base_goods_id, params);
              } else {
                target = await addGoodsBasic(params);
              }
              const data = target;
              this.loading = false;

              this.$message({
                type: "success",
                message: "提交成功",
              });
              await this.delPauseSave();
              this.$closeCurrentGoEdit(`/goods/manageG/BaseDataList`);
            } catch {
              this.loading = false;
            }
          }
        });
      },
      // 商品分类选择
      categoryChange(val, row) {
        // this.base_form.categoryPath = row;
        this.base_form.categoryId = val[val.length - 1];
        // this.base_form.categoryPath.push(this.$_common.deepClone(goodsItem));
      },
      // 品牌选择
      brandConfirm(val) {
        if (val.length > 1) {
          this.$message({
            type: "error",
            message: "请选择一个品牌！",
          });
          return;
        }
        this.base_form.brandName = val[0].title;
        this.base_form.brandId = val[0].id;
      },
      async getAllMerchantList() {
        const { data } = await getAllMerchantList();
        this.sel_cities = data;
      },
      // 商品分类列表
      async getAllCategoryPost() {
        const { data } = await getAllCategoryPost({
          enableStatus: 5,
        });

        if (JSON.stringify(data) === "{}") {
          this.category_data = [];
        } else {
          this.category_data = data;
        }
      },
      // 自定义选择即改变
      clickChange(event) {
        event.target.parentElement.parentElement.firstChild.click();
      },
      delAssistCate(index) {
        this.assist_cate.splice(index, 1);
      },
      addAssistCate() {
        this.assist_cate.push({
          assistCategoryPath: [],
        });
      },
      // 下一步
      tagNext() {
        if (this.page_tabs === "1") {
          this.$refs["base_form"].validate((valid) => {
            if (valid) {
              if (!this.base_form.masterUnit.unitId) {
                this.$message.warning("请选择基本单位");
                return;
              }
              this.page_tabs = "2";
              this.step_active = 2;
            }
          });
        } else if (this.page_tabs === "2") {
          if (!this.base_form.images.length) {
            this.$message.warning("请上传商品图片");
            return;
          }
          this.page_tabs = "3";
          this.step_active = 3;
        }
      },
      // 上一步
      tagLast() {
        if (this.page_tabs === "3") {
          this.step_active = 2;
          this.page_tabs = "2";
        } else if (this.page_tabs === "2") {
          this.page_tabs = "1";
          this.step_active = 1;
        }
      },
      tabClick() {
        if (this.page_tabs === "1") {
          this.step_active = 1;
        } else if (this.page_tabs === "2") {
          this.step_active = 2;
        } else if (this.page_tabs === "3") {
          this.step_active = 3;
        }
      },
      // 抄码商品切换
      isEqChange(val) {
        if (this.isEditSpec !== 4 && val === 5) {
          this.base_form.masterUnit = {
            isDefault: 5,
            isMaster: 5,
            weight: "",
            unitName: "",
            unitId: "",
            barCode: "",
          };
          this.base_form.branchUnit = [];
        }
      },
    },
  };
</script>
<style lang="scss">
  .goods-tab-view {
    .el-tabs__nav {
      padding-left: 28px !important;
    }
    .el-tabs__active-bar {
      left: 28px !important;
    }
  }
</style>
<style scoped lang="scss">
  .goods-tab-view {
    height: 64px;
    overflow: hidden;
    position: relative;
    .btn-view {
      z-index: 99;
      position: absolute;
      right: 36px;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .goodsCate {
    position: relative;
    margin-bottom: 2px;
  }
  .addCate {
    position: absolute;
    left: 290px;
    top: 7px;
  }
  .creat-shop {
    color: #1890ff;
    font-size: 12px;
  }
  .sku-name-item {
    background-color: #f4f4f4;
    padding: 5px 0;
  }
  ::v-deep .el-tabs__item {
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    color: #4f5e7b;
  }
  ::v-deep .is-active {
    color: #2153d4;
  }
  .order_top {
    width: 100%;
    background-color: #ffffff;
    border-radius: 3px;
    .order_top_content {
      padding: 20px 0 16px;
    }
  }
  .order_midden {
    margin-top: 16px;
    width: 100%;
    min-height: 600px;
    //height: 480px;
    background-color: #ffffff;
    border-radius: 3px;
    position: relative;
    .order_midden_top {
      position: absolute;
      top: 12px;
      right: 32px;
      z-index: 99;
      .salf-code {
        line-height: 32px;
        display: inline-block;
        font-size: 16px;
        font-weight: 500;
        color: #36b365;
        margin-right: 32px;
        vertical-align: middle;
      }
      .confirm {
        text-align: center;
        display: inline-block;
        width: 70px;
        height: 20px;
        //line-height: 20px;
        background-color: $base-color-blue;
        color: #ffffff;
        margin-right: 1px;
        margin-left: 10px;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
      }
      .con {
        width: 20px;
        text-align: center;
        display: inline-block;
        line-height: 20px;
        background-color: $base-color-blue;
        color: #ffffff;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
      }
    }
    .order_midden_left {
      margin-top: 16px;
      width: 95%;
      height: 350px;
      border-right: 1px solid #dee2ee;
    }
    .order_midden_m {
      margin-top: 16px;
      width: 95%;
      height: 350px;
      border-right: 1px solid #dee2ee;
    }
    .order_midden_right {
      margin-top: 16px;
    }
  }
  .order_midden_left_text {
    font-weight: bold;
    font-size: 16px;
    padding: 24px 20px 32px;
    .el-icon-arrow-right {
      font-weight: bold;
      margin-right: 4px;
      font-size: 14px;
    }
    .desc-span {
      font-size: 12px;
      font-weight: normal;
      color: #f57931;
    }
  }
  /* ::v-deep .el-tag {
    min-width: 80px;
    border-radius: 3px;
    font-size: 14px;
    margin-right: 12px;
    position: relative;
  }
  ::v-deep .el-tag__close {
    position: absolute;
    right: 5px;
    top: 5px;
  }*/
  .detail-edit-view {
    padding: 27px 30px;
  }
  .bottom-btn {
    width: 140px;
    height: 36px;
    border-radius: 4px;
    font-size: 14px;
  }
</style>
