<template>
  <div>
    <div class="from-content">
      <el-form :model="goodsForm" :rules="goodsRules" ref="goodsForm" label-width="150px" class="demo-ruleForm" label-position="right" v-loading="loading">
        <div class="form-section">
          <h3>基础信息</h3>
          <el-form-item label="福利渠道" class="w-630">{{ enterpriseName }}</el-form-item>
          <el-form-item label="礼品名称" class="w-630" prop="giftName">
             <el-input show-word-limit   type="text" v-model="goodsForm.giftName" :maxlength="30" placeholder="请输入礼品名称" />
          </el-form-item>
          <el-form-item label="礼品主图" required>
            <div class="member-upload-image">
              <div class="member-upload-image">
                <dm-upload-picture :action-url="actionUrl" :image-list="image" :max-image-length="maxlength" accept="image/jpeg, image/jpg, image/png, image/gif" :before-upload="beforeUpload" @uploadOnSuccess="uploadOnSuccess" @sortImg="sortImg" @deleteImage="deleteImage"></dm-upload-picture>
              </div>
              <span class="tip-warm" style="display:block">图片建议尺寸&nbsp;800*800px，格式&nbsp;jpg/png/gif，大小&nbsp;1M&nbsp;以内，你可以拖拽图片调整顺序，最多上传 5 张</span>
            </div>
          </el-form-item>
          <el-form-item label="礼品详情">
            <dm-editor :width="editorWidth" :value="goodsForm.giftDescrption" @change="handleChange"></dm-editor>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>规格/库存信息</h3>
          <el-form-item label="礼品规格">
            <div class="standard-info">
              <div>
                <div class="add-sku-content">
                  <div class="add-sku-list" v-if="goodsStandardInfo.length">
                    <div class="add-sku-item" v-for="(item, index) in goodsStandardInfo" :key="index" :class="[ index ? 'mt10' : '']">
                      <div class="sku-name">
                        <span class="sku-title">规格名:</span>
                        <span style="display:none">{{ refash }}</span>
                        <el-dropdown trigger="click" placement="bottom-start" @command="i => getSelected(i, item)">
                          <el-input v-model="item.specName" style="width:100px" size="smalll" placeholder="请选择" @input="value => spliceStandard(value, item)" @focus="getStdList(item)" @blur="addStandard(item)"></el-input>
                          <el-dropdown-menu slot="dropdown" style="height:300px;overflow-y:auto;min-width:200px;">
                            <el-dropdown-item style="width:200px" :command="i" v-for="i in standardList" :key="i.specId">{{ i.specName }}</el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                        <el-checkbox v-model="isStdImg" v-if="!index" class="ml20">添加规格图片</el-checkbox>
                        <!-- <span class="tip-warm ml20" v-if="!index">只有第一个规格的规格值可添加图片</span> -->
                        <span class="delete-btn" @click="deleteSku(index)"><i class="el-icon-error inline-block" style="width:16px;height:16px;font-size:16px"></i></span>
                      </div>
                      <div class="value-content" v-if="item.specName">
                        <span class="sku-value-title">规格值:</span>
                        <span style="display:none">{{ refash }}</span>
                        <div class="value-list">
                          <div class="value-item" v-for="(v, n) in item.valueList" :key="n">
                            <el-dropdown trigger="click" placement="bottom-start" @command="i => getSelectedValue(i, item, n)">
                              <el-input v-model="v.specStandardValueName" style="width:160px" size="smalll" placeholder="请选择" @input="value => spliceStandardValue(value, item)" @focus="getStdValueList(value, item)" @blur="addStandardValue(item, n)"></el-input>
                              <el-dropdown-menu slot="dropdown" style="height:300px;overflow-y:auto;min-width:200px;">
                                <el-dropdown-item style="width:200px" :command="m" v-for="m in standardValueList" :key="m.specValueId">{{ m.specValue }}</el-dropdown-item>
                              </el-dropdown-menu>
                            </el-dropdown>
                            <div class="table-img" v-if="!index && isStdImg && item.valueList.length">
                              <div class="triangle"></div>
                              <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false" with-credentials :on-success="(response, file, fileList) => tableUploadSuccess(response, file, fileList, v)" :before-upload="tableBeforeUpload">
                                <img v-if="v.propImg" :src="v.propImg" class="avatar" />
                                <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size:28px"></i>
                              </el-upload>
                              <p class="img-modal" v-if="v.propImg">
                                <i class="el-icon-delete" @click="deleteImg(v)"></i>
                              </p>
                              <p style="font-size:12px;color:#FF5152;position:absolute;bottom:-32px" v-if="!v.propImg">请添加规格图片</p>
                            </div>
                            <span class="el-icon-error" @click="deleteValue(item, v, index, n)"></span>
                          </div>
                          <el-button type="text" @click="addValue(item)">添加规格值</el-button>
                          <p v-if="!index && isStdImg" :class="[item.valueList.length ? 'hasValueList' : 'emptyValueList']">仅支持为第一组规格设置规格图片，买家选择不同规格会看到对应规格图片，建议尺寸 800*800px。</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="add-sku">
                    <div class="add-sku-button">
                      <el-button v-show="goodsStandardInfo.length < 3" @click="addSku" type="text">添加规格项目</el-button>
                    </div>
                  </div>
                </div>
                <p class="tip-warm w-900">如有颜色、尺码等多种规格参数，请添加商品规格</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="规格明细" v-if="goodsSkuList.length > 0 && goodsStandardInfo.length > 0">
            <div class="sku-table-content" v-if="goodsSkuList.length > 0 && goodsStandardInfo.length > 0">
              <el-table class="sku-table" :data="goodsSkuList" :span-method="objectSpanMethod" :header-cell-class-name="starAdd">
                <el-table-column v-for="(i, k) in skuCols" :label="i" :key="i" :class-name="k == skuCols.length - 1 ? 'pad-l-20' : 'right-border'">
                  <template slot-scope="scope">{{ scope.row.cols[k] }}</template>
                  <span style="display:none">{{ refash }}</span>
                </el-table-column>
                <el-table-column label="成本" width="145px;">
                  <template slot-scope="scope">
                    <div class="el-form-item" :class="skuSellObj[scope.row.mapId].giftSkuCostPriceStatus ? '' : 'is-error'">
                      <dm-input-amount v-if="skuSellObj[scope.row.mapId]" width="125px" class="input-number mr10" :max="999999.99" :min="0" v-model.trim="skuSellObj[scope.row.mapId].giftSkuCostPrice" :precision="2" controls-position="right" @blur="handleValidIntegral(skuSellObj[scope.row.mapId].giftSkuCostPrice, scope.row.mapId, 2)"></dm-input-amount>
                    </div>
                  </template>
                  <template v-slot:header>
                    <!-- <span>成本</span> -->
                    <el-tooltip open-delay="200" effect="dark" style="width:250px" placement="top">
                      <span class="undeline-dash">成本(元)</span>
                      <span slot="content">
                        若SKU的成本未填写则按照SPU价格计算
                      </span>
                    </el-tooltip>
                    <el-popover placement="top" trigger="click" ref="popover3">
                      <div>
                        <dm-input-amount v-model.trim="handleData.giftSkuCostPrice" width="140" style="margin-left:-2px;" controls-position="right" precision="2" :min="0" :max="999999.99"></dm-input-amount>
                      </div>
                      <div class="popver-button" style="margin-top:18px;text-align:right">
                        <el-button type="dafault" class="cancel-style" size="small" @click="$refs.popover3.showPopper = false">取消</el-button>
                        <el-button type="primary" size="small" class="ml10 ml10" @click="handleCostPrice">确认</el-button>
                      </div>
                      <el-tooltip slot="reference" popper-class="batch-style" visible-arrow placement="top" content="批量编辑">
                        <i class="el-icon-edit-outline ml8"></i>
                      </el-tooltip>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="可占库存" width="190px;">
                  <template slot-scope="scope">
                    <div class="el-form-item" :class="skuSellObj[scope.row.mapId].stockStatus ? '' : 'is-error'">
                      <dm-input-number v-if="skuSellObj[scope.row.mapId]" width="125px" class="input-number mr10" @input="handleSpuStock" v-model.trim="skuSellObj[scope.row.mapId].stock" :max="999999" :min="0" :precision="0" controls-position="right" @blur="handleValidStock(skuSellObj[scope.row.mapId].stock, scope.row.mapId, 2)"></dm-input-number>
                    </div>
                  </template>
                  <template v-slot:header>
                    <span>可占库存</span>
                    <el-popover placement="top" trigger="click" ref="popover2">
                      <div>
                        <dm-input-number v-model.trim="handleData.stock" width="140" style="margin-left:-2px;" controls-position="right" precision="0" :min="0" :max="999999"></dm-input-number>
                      </div>
                      <div class="popver-button" style="margin-top:18px;text-align:right">
                        <el-button type="dafault" class="cancel-style" size="small" @click="$refs.popover2.showPopper = false">取消</el-button>
                        <el-button type="primary" size="small" class="ml10 ml10" @click="handleStock">确认</el-button>
                      </div>
                      <el-tooltip slot="reference" popper-class="batch-style" visible-arrow placement="top" content="批量编辑">
                        <i class="el-icon-edit-outline ml8"></i>
                      </el-tooltip>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="sku编码">
                  <template slot-scope="scope" style="width:120px">
                    <el-input v-if="skuSellObj[scope.row.mapId]" v-model.trim="skuSellObj[scope.row.mapId].giftSkuCode" type="text" placeholder="请输入" @blur="handleValiedSkuCode(skuSellObj[scope.row.mapId].giftSkuCode, scope.row.mapId, 2)"></el-input>
                  </template>
                  <template v-slot:header>
                    <span>sku编码</span>
                    <el-popover placement="top" trigger="click" ref="popover1">
                      <div>
                        <el-input class="hidden-limit" placeholder="请输入" v-model.trim="handleData.giftSkuCode" width="140" @blur="handleValiedSkuCode(handleData.giftSkuCode, '', 1)" style="margin-left:-2px;"></el-input>
                      </div>
                      <div class="popver-button" style="margin-top:18px;text-align:right">
                        <el-button type="dafault" class="cancel-style" size="small" @click="$refs.popover1.showPopper = false">取消</el-button>
                        <el-button type="primary" size="small" class="ml10 ml10" @click="handleSkuCode">确认</el-button>
                      </div>
                      <el-tooltip slot="reference" popper-class="batch-style" visible-arrow placement="top" content="批量编辑">
                        <i class="el-icon-edit-outline ml8"></i>
                      </el-tooltip>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="礼品条形码" style="width:120px">
                  <template slot-scope="scope">
                    <el-input v-if="skuSellObj[scope.row.mapId]" v-model.trim="skuSellObj[scope.row.mapId].skuBarCode" type="text" placeholder="请输入" @blur="handleValiedskuBarCode(skuSellObj[scope.row.mapId].skuBarCode, scope.row.mapId, 2)"></el-input>
                  </template>
                  <template v-slot:header>
                    <span>礼品条形码</span>
                    <el-popover placement="top" trigger="click" ref="popover">
                      <div>
                        <el-input class="hidden-limit" placeholder="请输入" v-model.trim="handleData.skuBarCode" width="140" @blur="handleValiedskuBarCode(handleData.skuBarCode, '', 1)" style="margin-left:-2px;"></el-input>
                      </div>
                      <div class="popver-button" style="margin-top:18px;text-align:right">
                        <el-button type="dafault" class="cancel-style" size="small" @click="$refs.popover.showPopper = false">取消</el-button>
                        <el-button type="primary" size="small" class="ml10 ml10" @click="handleBarCode">确认</el-button>
                      </div>
                      <el-tooltip slot="reference" popper-class="batch-style" visible-arrow placement="top" content="批量编辑">
                        <i class="el-icon-edit-outline ml8"></i>
                      </el-tooltip>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <p style="color:#909399;font-size:12px;line-height:17px;font-weight:400;margin-top:8px">可点击表格标题处&nbsp;<i class="el-icon-edit-outline"></i>&nbsp;按钮进行批量设置</p>
          </el-form-item>
          <el-form-item label="成本" class="w-630" prop="costPrice" :rules="[{ validator: costPriceValide, trigger: 'blur' }]">
            <dm-input-amount v-model="goodsForm.costPrice" width="180" :min="0" :max="999999.99" :precision="2" :disabled="goodsStandardInfo.length > 0"></dm-input-amount>
          </el-form-item>
          <el-form-item label="可占用库存" class="w-630" prop="stock">
            <dm-input-number v-model="goodsForm.stock" width="180" :min="0" :max="999999" :precision="0" :disabled="goodsStandardInfo.length > 0"></dm-input-number>
          </el-form-item>
          <el-form-item prop="marketPrice" label="市场价:">
            <dm-input-amount v-model="goodsForm.marketPrice" width="180" :min="0" :max="999999.99" :precision="2"></dm-input-amount>
            <div>
              <span class="tip-warm">市场价在礼品详情会以划线形式显示。</span>
              <el-popover placement="top-start" width="395" trigger="hover">
                <img style="width:360px" src="../../assets/images/eg2.png" alt />
                <el-button slot="reference" type="text" style="margin-left:15px;font-size:12px">查看示例</el-button>
              </el-popover>
            </div>
          </el-form-item>
          <el-form-item label="礼品编码" class="w-630" prop="giftNo" :rules="[{ validator: validateGoodsCode, trigger: 'blur' }]">
            <el-input style="width:260px" v-model="goodsForm.giftNo" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="礼品条形码" class="w-630" prop="giftBarNo" :rules="[{ validator: validateGoodsBarCode, trigger: 'blur' }]">
            <el-input style="width:260px" v-model="goodsForm.giftBarNo" placeholder="请输入"></el-input>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>福利设置</h3>
          <!-- 实物 -->
          <el-form-item label="配送方式" prop="deliveryList">
            <template>
              <el-checkbox-group v-model="goodsForm.deliveryList" @change="changeDelivery">
                <el-checkbox label="1">快递发货</el-checkbox>
                <el-checkbox label="2">门店自提</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
          <el-form-item label="设置自提点" v-if="goodsForm.deliveryType == 2 || goodsForm.deliveryList.length == 2">
            <template>
              <select-pickup-store :gift-id="giftId" :is-edit="isEdit" :data="diliveryData" @change="changeStoreSelect"></select-pickup-store>
            </template>
          </el-form-item>
          <el-form-item label="库存消耗方式" prop="checkList">
            <template>
              <el-checkbox-group v-model="goodsForm.checkList" @change="changeStockUse" :disabled="isEdit">
                <el-checkbox label="0">
                  <el-tooltip class="tips-content" effect="dark" open-delay="200" popper-class="store-tips" placement="top-start">
                    <div slot="content" style="width:245px">固定库存：通过占用的方式获得固定可用库存，不会被其他应用/活动所消耗。</div>
                    <span class="inline-block ml30 dash-style">固定库存</span>
                  </el-tooltip>
                </el-checkbox>
                <el-checkbox label="1" style="margin-left:50px">
                  <el-tooltip class="tips-content" effect="dark" open-delay="200" popper-class="store-tips" placement="top-start">
                    <div slot="content" style="width:245px">实时库存：不占用库存，使用福利中心“可占库存”，与其他应用使用同个库存。</div>
                    <span class="inline-block ml30 dash-style">实时库存</span>
                  </el-tooltip>
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>售后服务</h3>
          <el-form-item prop="refundFlag" label="支持买家申请退货">
            <template>
              <div>
                <el-radio v-model="goodsForm.refundFlag" :label="1">支持</el-radio>
                <el-radio v-model="goodsForm.refundFlag" :label="0">不支持</el-radio>
              </div>
              <span class="tip-warm" style="display:block">若商品不支持退货，则该礼品出库后不支持生成退货单</span>
            </template>
          </el-form-item>
        </div>
        <div class="form-section mb56">
          <h3>权限设置</h3>
          <el-form-item label="操作人权限" required>
            <!-- <dm-acc-group-select :etype.sync="goodsForm.operAuthType" :group-ids.sync="goodsForm.operAuthPre" @change="updateGroupList" /> -->
            <dm-acc-group-select ref="accg" input-width="250px" :scene-type="sceneType" :relation-id="relationId" :is-echo="isEcho" />
          </el-form-item>
        </div>
        <div class="fixed-btn">
          <el-button type="primary" @click="submitForm('goodsForm')" v-if="isEdit">保存</el-button>
          <el-button type="primary" @click="submitForm('goodsForm')" v-else>确认新建</el-button>
          <!-- <dm-perm-button type="primary" @click="submitForm('goodsForm')" v-if="isEdit">保存</dm-perm-button>
          <dm-perm-button type="primary" @click="submitForm('goodsForm')" v-else>确认新建</dm-perm-button> -->
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { request } from '../../utils/request';
// import { mapGetters } from 'vuex';
// import qs from 'qs';
// import copy from '../../utils/clone';
import selectPickupStore from './module/select-pickup-store';
import { deepClone } from '../../utils/index';
import api from '@/api/gift.js';
import uploadUrl from '@/api/common.js';
const {
  giftStandardList,
  giftStandardNew,
  giftStandardValueList,
  giftStandardValueNew,
  giftGet,
  giftUpdate,
  giftSave,
  getGiftId,
  // getOperatorList,
  getGiftShopList } = api;
export default {
  components: {
    // importCoupon
    selectPickupStore,
  },
  data() {
    let costPriceValide = (rule, value, callback) =>{
      if(value){
        const regExp = /[\u4e00-\u9fa5]/g;
        if(regExp.test(value)) {
          return callback(new Error('成本只能是数字'));
        }
      }
      callback();
    };
    let validateGoodsCode = (rule, value, callback) => {
      if (value) {
        if(value.split('').length > 32){
          return callback(new Error('礼品编码最多32位'));
        }
        let regExp = /^[A-Za-z0-9\-\—]{1,32}$/;
        if (!regExp.test(value)) {
          return callback(new Error('礼品编码只支持数字或字母或-或—'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let validateGoodsBarCode = (rule, value, callback) => {
      if (value) {
        if(value.split('').length > 32){
          return callback(new Error('礼品条形码最多32位'));
        }
        let regExp = /^[a-zA-Z0-9]{1,32}$/;
        if (!regExp.test(value)) {
          return callback(new Error('礼品条形码只能是数字或字母'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      uploadUrl: uploadUrl,
      bread: [
        {
          breadName: '福利中心'
        },
        {
          breadName: '礼品管理'
        },
        {
          breadPath: '/gift-manage/real-gift',
          breadName: '实物礼品'
        },
        {
          breadName: '新建礼品'
        }
      ],
      banthStockType: 0,
      goodsForm: {
        enterpriseName: '',
        giftName: '', // 礼品名称
        marketPrice: '', // 礼品市场价
        spuList: [
          {
            giftNo: '',
            costPrice: undefined,
            stock: undefined,
            giftBarNo: ''
          }
        ],
        giftImages: '', // 礼品主图URL，分割
        giftDescrption: '', // 礼品详情
        limitTimeBegin: '',
        checkList: [],
        refundFlag: 0,
        operAuthType: '', // 操作人权限
        operAuth: '',
        operAuthPre: [],
        shopCodeList: [],
        deliveryType: [], // 配送方式 1物流发货 2门店自提 3文本券码
        stockUseType: '', // 库存使用类型（0:占用,1:动态 , 2占用+动态）
        deliveryList: [],
        costPrice: '',
        stock: 0,
        giftNo: '',
        giftBarNo: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date().getTime();
        }
      },
      goodsRules: {
        giftName: [ { required: true, message: '请输入礼品名称', trigger: 'blur' } ],
        costPrice: [ { required: true, message: '请输入成本',  trigger: 'blur' } ],
        stock: [ { required: true, message: '请输入可占用库存',  trigger: 'blur' } ],
        // refundFlag: [ { required: true, message: '请选择是否支持退款', trigger: 'change' } ],
        deliveryList: [ { required: true, message: '请选择配送方式', trigger: 'change' } ],
        checkList: [ { required: true, message: '请选择库存消耗方式', trigger: 'change' } ],
        // operAuthType: [ { required: true, message: '请选择操作人权限', trigger: 'change' } ],
      },
      validateGoodsCode,
      validateGoodsBarCode,
      costPriceValide,
      // 规格信息
      goodsStandardInfo: [],
      standardList: [], // 当前操作的规格列表
      searchStandard: '', // 规格搜索字段
      standardValueList: [], // 规格值列表
      searchStandardValue: '', // 规格值搜索字段
      goodsSkuList: [], // sku列表数据
      skuCols: [],
      stValCount: [],
      skuSellObj: {},
      skuSellObj2: {},
      stockObj: {},
      isStdImg: false,
      cordList: [], // 礼品分类
      // goodsType: 1, // 1 实物 2虚拟
      giftId: '',
      gooodsId: '',
      editorWidth: 900,
      refash: false,
      // 图片墙数据
      // projectName: 'welfare', // 当前项目名(必传参数)
      // wxFlag: '1', // '1': 表示需要返回微信图片地址(可选参数),插件内已默认 '1'
      actionUrl: '/api-plug/upload-images', // 必选参数，上传的相对地址 String 类型,切勿硬编码写死地址
      maxlength: 5, // 图片数量 默认 5
      image: [],
      // 规格值图片上传
      // uploadAction: window.location.origin + '/api-marketing/upload/upload-image',
      uploadAction: 'https://four.gicdev.com/api-marketing/upload/upload-image',
      // uploadAction: '/welfare/upload/upload-image',
      openStorePick: 0,
      btnLoading: false,
      loading: false,
      enterpriseName: '', // 商户名称
      handleData: {
        giftSkuCostPrice: '',
        stock: undefined,
        giftSkuCode: '',
        skuBarCode: ''
      },
      isEdit: false,
      diliveryData: {
        shopSelectType: '',
        shopCodeList: [],
        shopNum: '',
      },
      relationId: '', // 账号分组relationId
      isEcho: false, // 控制操作人权限是否回显数据
      sceneType: 10, // 场景值，现在测试使用，后期提供确定的
    };
  },
  mounted() {
    this.$emit('updateBread', this.bread);
    this.$emit('showAside', true);
    this.getLoginUser();
    this.giftId = this.$route.query.giftId;
    if (this.giftId) {
      this.bread[3].breadName = '编辑礼品';
      this.getMess();
      this.isEdit = true;
      this.getShopList();
      this.isEcho = true;
      this.relationId = this.$route.query.giftId;
    }else{
      this.getGiftId();
    }
    this.getStandardList(); // 获取规格列表
  },
  methods: {
    getGiftId(){
      // let giftId;
      getGiftId().then(res =>{
        if(res.code === '0000'){
          this.giftId = res.result;
          this.relationId = res.result;
        }else{
          this.$message.error(res.message);
        }
      });
    },
    // 表头添加必填标识符
    starAdd(obj){
      if(obj.column.label === '可占库存' || obj.column.label === '成本') {
        return 'star';
      }
    },
    changeDelivery(value){
      if(value.length > 1){
        this.goodsForm.deliveryType = '1,2';
      }else{
        this.goodsForm.deliveryType = value[0];
      };
    },
    // 自提点选择
    changeStoreSelect(val){
      this.diliveryData.shopSelectType = val.shopSelectType;
      this.diliveryData.shopCodeList = val.shopCodeList;
      this.diliveryData.shopNum = val.shopNum;
    },
    // 处理库存消耗方式
    changeStockUse(value){
      if(value.length > 1){
        this.goodsForm.stockUseType = 2;
      }else{
        this.goodsForm.stockUseType = value[0];
      };
    },
    // 获取商户信息
    getLoginUser(){
      request({ url: '/gic-auth-web/user/get-login-user' }).then(res => {
        this.enterpriseName = res.result.enterpriseName;
      });
    },
    // 自提点回显
    getShopList(){
      getGiftShopList({ id: this.giftId }).then(res => {
        if(res.code === '0000'){
          res.result.forEach((item) =>{
            this.diliveryData.shopCodeList.push(item.shopCode);
          });
        }else{
          this.$message.error(res.message);
        }
      });
    },
    getMess() {
      let params = {
        id: this.giftId
      };
      this.$emit('updateLoading');
      giftGet(params)
        .then(res => {
          if (res.code === '0000') {
            let resResult = res.result;
            this.goodsForm.giftName = resResult.giftName; // 礼品名称
            this.goodsForm.marketPrice = resResult.marketPrice; // 市场价
            this.goodsForm.stock = resResult.stock; // 库存
            this.goodsForm.giftNo = resResult.giftNo; // 礼品编码
            this.goodsForm.giftBarNo = resResult.giftBarNo; // 礼品条形码
            // this.goodsForm.operAuthType = resResult.operAuthType; // 操作人权限
            // this.goodsForm.operAuthPre = resResult.operAuth ? resResult.operAuth.split(',') : [];
            this.goodsForm.checkList = resResult.stockUseType == 2 ? [ '1', '0' ] : (resResult.stockUseType == 1 ? [ '1' ] : [ '0' ]); // 库存消耗方式
            this.goodsForm.deliveryType = resResult.deliveryType;
            if(this.goodsForm.deliveryType == '1,2'){
              this.goodsForm.deliveryList = [ '1', '2' ];
            }else{
              this.goodsForm.deliveryList = [ this.goodsForm.deliveryType ];
            };
            this.diliveryData.shopSelectType = resResult.shopSelectType;
            this.diliveryData.shopNum = resResult.shopNum != '0' ? resResult.shopNum : '0';
            this.goodsForm.giftImages = resResult.giftImages;
            this.goodsForm.stockUseType = resResult.stockUseType;
            let img = resResult.giftImages.split(',');
            if (img.length) {
              for (let item of img) {
                this.image.push({
                  url: item
                });
              }
            } // 礼品主图
            this.goodsForm.giftDescrption = resResult.giftDescrption; // 礼品详情
            this.goodsForm.refundFlag = resResult.refundFlag; // 是否支持退货
            this.goodsStandardInfo = resResult.giftSpecInfo ? JSON.parse(resResult.giftSpecInfo) : []; // 礼品规格信息

            let skuList = resResult.skuList || []; // 礼品规格值信息
            if(this.goodsStandardInfo.length > 0){
              if(skuList.length > 1){
                let arr2 = [];
                for(let key1 in skuList){
                  arr2.push(skuList[key1].giftSkuCostPrice);
                }
                let max = Math.max.apply(null, arr2);
                let min = Math.min.apply(null, arr2);
                if(max === min){
                  this.goodsForm.costPrice = min;
                }else{
                  this.goodsForm.costPrice = min + '~' + max;
                }
              }else if(skuList.length === 1){
                this.goodsForm.costPrice = skuList[0].giftSkuCostPrice;
              }
            }else{
              this.goodsForm.costPrice = Number(resResult.costPrice).toFixed(2);
            }
            let mapData = [];
            let skuSellObj = {};
            if (skuList.length > 0) {
              for (let i = 0; i < skuList.length; i++) {
                mapData.push({
                  mapId: '',
                  id: [],
                  giftSkuId: skuList[i].giftSkuId,
                  giftSkuCostPrice: skuList[i].giftSkuCostPrice,
                  giftSkuCode: skuList[i].giftSkuCode,
                  skuBarCode: skuList[i].skuBarCode,
                  stock: skuList[i].stock,
                  giftSkuStrand: skuList[i].giftSkuStrand,
                  giftId: skuList[i].giftId
                });
                if(skuList[i].giftSkuStrand){
                  for (let j = 0; j < JSON.parse(skuList[i].giftSkuStrand).length; j++) {
                    mapData[i].id.push(JSON.parse(skuList[i].giftSkuStrand)[j].specStandardValueId);
                  }
                  mapData[i].mapId = mapData[i].id.join('_');
                }
              }
              for (let item of mapData) {
                skuSellObj[item.mapId] = {
                  skuBarCode: item.skuBarCode,
                  giftSkuCode: item.giftSkuCode,
                  giftSkuCostPrice: item.giftSkuCostPrice,
                  stock: item.stock,
                  giftSkuCostPriceStatus: true,
                  stockStatus: true,
                  giftSkuId: item.giftSkuId,
                };
              }
              this.skuSellObj = deepClone(skuSellObj);
            }
            if (this.goodsStandardInfo.length > 0) {
              this.isStdImg = this.goodsStandardInfo[0].standardimg === 2 ? true : false;
            } else {
              this.isStdImg = false;
            }
            if (this.goodsStandardInfo.length > 0) {
              this.getSkuList();
            }
          } else {
            this.$message.error(res.message);
          }
        }).finally(() => this.$emit('updateLoading'));
    },
    // 上传前
    beforeUpload(file) {
      if (file.size > 1 * 1024 * 1024) {
        this.$message.error('请上传小于1MB的图片');
        return false;
      }
      // if (file.width < 800 || file.width / file.width != 1 / 1) {
      //   this.$message.error('请上传宽度≥800px，宽高比1：1的图片');
      //   return false;
      // }
      return true;
    },
    // 上传成功 返回的图片对象 里面有图片 大小 类型 等相关信息
    uploadOnSuccess(obj) {
      // 目前返回两个参数 {res:res,file:file}
      let url = obj.res.result[0];
      this.image.push(url);
      let handelImage = [];
      this.image.forEach((item, index) =>{
        handelImage[index] = item.url;
      });
      this.goodsForm.giftImages = handelImage.join('');
    },
    // 删除图片 返回图片列表的索引 你可以根据这个索引去找对应图片的id
    deleteImage(i) {
      this.image.splice(i, 1);
      let handelImage = [];
      this.image.forEach((item, index) =>{
        handelImage[index] = item.url;
      });
      this.goodsForm.giftImages = handelImage.join('');
    },
    sortImg(val) {
      this.image = val;
      let handelImage = [];
      this.image.forEach((item, index) =>{
        handelImage[index] = item.url;
      });
      this.goodsForm.giftImages = handelImage.join('');
    },
    handleChange(val) {
      this.goodsForm.giftDescrption = val;
    },
    /** *******************规格相关 start*********************/
    // 点击规格下拉选中
    getSelected(i, item) {
      item.valueList = [ { specStandardValueName: '', specStandardValueId: '' } ];
      item.specName = i.specName;
      item.specId = i.specId;
      this.refash = !this.refash;
      this.getSkuList();
    },
    // 添加规格
    addSku() {
      this.goodsStandardInfo.push({
        specId: '',
        specName: '',
        standardimg: 1,
        valueList: [ { specStandardValueName: '', specStandardValueId: '' } ]
      });
      this.refash = !this.refash;
      this.getSkuList();
    },
    // 规格名称添加限制字数
    spliceStandard(value, item) {
      // this.$nextTick(() => {
      //   // item.specName = common.getInputVal(value, 10);
      // });
      this.searchStandard = item.specName;
      this.getStandardList(item, null, this.searchStandard);
    },
    // 获取规格列表
    getStdList(item) {
      let arrIds = [];
      for (let item of this.goodsStandardInfo) {
        if (item.specId && item.specName) {
          arrIds.push(item.specId);
        }
      }
      let ids = arrIds.join(',');
      this.getStandardList(item, ids, '');
    },
    // 获取规格列表
    getStandardList(item, ids, search) {
      let speIds;
      if (ids) {
        speIds = ids;
      } else {
        speIds = '';
      }
      let params = {
        speIds: speIds,
        search: search,
      };
      giftStandardList(params).then(res => {
        if (res.code === '0000') {
          if (res.result) {
            this.standardList = res.result || [];
          } else {
            this.standardList = [];
          }
          this.searchStandard = '';
        } else {
          this.standardList = [];
          this.$message.error(res.data.message);
        }
      });
    },
    // 新增规格
    addStandard(item) {
      if (item.specName && !item.specId) {
        // 新增的
        let params = {
          // giftId: this.giftId,
          specName: item.specName
        };
        giftStandardNew(params).then(res => {
          if (res.data.code === '0000') {
            item.specId = res.result;
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    // 删除规格
    deleteSku(index) {
      this.goodsStandardInfo.splice(index, 1);
      // if(!this.goodsStandardInfo.length){
      this.goodsForm.costPrice = '';
      // };
      this.getSkuList();
    },

    // 规格值
    getSelectedValue(i, item, index) {
      item.valueList[index].specStandardValueName = i.specValue;
      item.valueList[index].specStandardValueId = i.specValueId;
      this.refash = !this.refash;
      this.getSkuList();
    },
    spliceStandardValue(value, item) {
      this.searchStandardValue = value;
      this.getValueId(item);
    },
    // 去重规格值
    getStdValueList(value, item) {
      this.refash = !this.refash;
      this.getValueId(item);
    },
    // 获取规格值列表
    getValueId(item) {
      let standardValueIdArr = [];
      for (let i of item.valueList) {
        if (i.specStandardValueId && i.specStandardValueName) {
          standardValueIdArr.push(i.specStandardValueId);
        }
      }
      let params = {
        specId: item.specId,
        specValueIds: standardValueIdArr.join(','),
        search: this.searchStandardValue
      };
      giftStandardValueList(params).then(res => {
        if (res.code === '0000') {
          if (res.result) {
            this.standardValueList = res.result || [];
          } else {
            this.standardValueList = [];
          }
          this.searchStandardValue = '';
        } else {
          this.standardValueList = [];
          this.$message.error(res.message);
        }
      });
    },
    // 保存规格值
    addStandardValue(item, index) {
      if (item.valueList[index].specStandardValueName && !item.valueList[index].specStandardValueId) {
        let params = {
          specId: item.specId,
          specValueName: item.valueList[index].specStandardValueName
        };
        giftStandardValueNew(params).then(res => {
          if (res.code === '0000') {
            if (res.result) {
              let repeatId = '';
              let arr = deepClone(item.valueList);
              let arr1 = deepClone(arr);
              arr1.splice(index, 1);
              if (
                arr1.find(item => {
                  return item.specStandardValueId === res.result;
                })
              ) {
                repeatId = arr1.find(item => {
                  return item.specStandardValueId === res.result;
                }).specStandardValueId;
              } else {
                repeatId = '';
              }
              // 添加重复
              if (repeatId !== res.result) {
                item.valueList[index].specStandardValueId = res.result;
                this.refash = !this.refash;
                this.getSkuList();
              } else {
                this.$message.error('禁止重复添加');
                item.valueList[index].specStandardValueName = '';
                return false;
              }
            }
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    // 添加规格值
    addValue(item) {
      item.valueList.push({ specStandardValueName: '', specStandardValueId: '' });
      this.getSkuList();
      this.refash = !this.refash;
    },
    // 删除规格值
    deleteValue(item, v, index, n) {
      item.valueList.splice(n, 1);
      // 删除掉sku数据
      let goodsSkuListCopy = deepClone(this.goodsSkuList);
      // return;
      for (let m = 0; m < goodsSkuListCopy.length; m++) {
        if (v.specStandardValueId && goodsSkuListCopy[m].mapId.indexOf(v.specStandardValueId) !== -1) {
          goodsSkuListCopy.splice(m, 1);
          m = 0;
        } else if (v.specStandardValueId === '') {
          goodsSkuListCopy.splice(n, 1);
        }
      }
      this.goodsSkuList = deepClone(goodsSkuListCopy);
      this.getSkuList();
      this.handleCostPrice();
      this.handleStock();
    },
    // 表格里面的图片上传成功
    tableUploadSuccess(response, file, fileList, item2) {
      if (response.code === '0000') {
        item2.propImg = response.result.url;
        this.$message.success('上传成功');
        this.refash = !this.refash;
      } else {
        this.$message.error(response.message);
      }
    },
    // 表格里面的图片上传前面
    tableBeforeUpload(file) {
      // if (file.size > 2 * 1024 * 1024) {
      //   this.$message.error('请上传小于2MB的图片');
      //   return false;
      // }
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg' && file.type !== 'image/gif') {
        this.$message.error('请上传jpg，png，gif格式的图片');
        return false;
      }
      // let that = this;
      // return new Promise(function(resolve, reject) {
      //   let reader = new FileReader();
      //   reader.onload = function(event) {
      //     let image = new Image();
      //     image.onload = function() {
      //       let width = this.width;
      //       let height = this.height;
      //       if (width < 200 || width / height < 1 / 1) {
      //         that.$message.error('请上传正确的图片尺寸');
      //         reject();
      //       }
      //       resolve();
      //     };
      //     image.src = event.target.result;
      //   };
      //   reader.readAsDataURL(file);
      // });
    },
    // 删除规格图片
    deleteImg(item) {
      item.propImg = '';
      this.refash = !this.refash;
    },

    objectSpanMethod({ rowIndex, columnIndex }) {
      let len = this.stValCount.length;
      if (columnIndex < len) {
        let count1 = this.stValCount[columnIndex];
        let count2 = this.stValCount[len - 1];
        if (!(count1 && count2)) {
          return { rowspan: 0, colspan: 0 };
        }
        let rowspan = count2 / count1;
        if (rowIndex % rowspan === 0) {
          return { rowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
    },
    handleStock(){
      for (let item in this.skuSellObj) {
        this.skuSellObj[item] = {
          giftSkuCostPrice: this.handleData.giftSkuCostPrice ? this.handleData.giftSkuCostPrice : this.skuSellObj[item].giftSkuCostPrice,
          stock: this.handleData.stock ? this.handleData.stock : this.skuSellObj[item].stock,
          giftSkuCode: this.handleData.giftSkuCode ? this.handleData.giftSkuCode : this.skuSellObj[item].giftSkuCode,
          skuBarCode: this.handleData.skuBarCode ? this.handleData.skuBarCode : this.skuSellObj[item].skuBarCode,
          stockStatus: true,
          giftSkuCostPriceStatus: true,
          giftSkuId: this.skuSellObj[item].giftSkuId,
          stockAlter: 0,
          stockType: 0
        };
        if(this.isEdit){
          if(Number(this.stockObj[item]) > Number(this.skuSellObj[item].stock)){
            this.skuSellObj[item].stockType = 0;
            this.skuSellObj[item].stockAlter = Number(this.stockObj[item]) - Number(this.skuSellObj[item].stock);
          }else{
            this.skuSellObj[item].stockType = 1;
            this.skuSellObj[item].stockAlter = Number(this.skuSellObj[item].stock) - Number(this.stockObj[item]);
          }
          if(!this.stockObj[item]){
            this.skuSellObj[item].stockType = 1;
            this.skuSellObj[item].stockAlter = this.skuSellObj[item].stock;
          }
        }
      }
      this.handleData.stock = undefined;
      this.handleSpuStock();
    },
    handleCostPrice(){
      const regExp = /[\u4e00-\u9fa5]/g;
      if(regExp.test(this.handleData.giftSkuCostPrice)) {
        this.handleData.giftSkuCostPrice = '';
        this.$message.error('成本只能是数字');
      }
      for (let item in this.skuSellObj) {
        this.skuSellObj[item] = {
          giftSkuCostPrice: this.handleData.giftSkuCostPrice ? this.handleData.giftSkuCostPrice : this.skuSellObj[item].giftSkuCostPrice,
          stock: this.handleData.stock ? this.handleData.stock : this.skuSellObj[item].stock,
          giftSkuCode: this.handleData.giftSkuCode ? this.handleData.giftSkuCode : this.skuSellObj[item].giftSkuCode,
          skuBarCode: this.handleData.skuBarCode ? this.handleData.skuBarCode : this.skuSellObj[item].skuBarCode,
          stockStatus: true,
          giftSkuCostPriceStatus: true,
          giftSkuId: this.skuSellObj[item].giftSkuId,
          stockAlter: 0,
          stockType: 0
        };
      }
      this.handleData.giftSkuCostPrice = '';
      let arr1 = Object.keys(this.skuSellObj);
      if(arr1.length > 1){
        let arr2 = [];
        for(let key1 in this.skuSellObj){
          arr2.push(this.skuSellObj[key1].giftSkuCostPrice);
        }
        let max = Math.max.apply(null, arr2);
        let min = Math.min.apply(null, arr2);
        if(max === min){
          this.goodsForm.costPrice = min;
          // this.goodsForm.spuList[0].costPrice = min;
        }else{
          // this.goodsForm.spuList[0].costPrice = min + '~' + max;
          this.goodsForm.costPrice = min + '~' + max;
        }
      }else if(arr1.length === 1){
        for(let key1 in this.skuSellObj){
          this.goodsForm.costPrice = this.skuSellObj[key1].giftSkuCostPrice;
        }
        // this.goodsForm.spuList[0].costPrice = this.skuSellObj[0].giftSkuCostPrice;
      }
    },
    handleSkuCode(){
      for (let item in this.skuSellObj) {
        this.skuSellObj[item] = {
          giftSkuCostPrice: this.handleData.giftSkuCostPrice ? this.handleData.giftSkuCostPrice : this.skuSellObj[item].giftSkuCostPrice,
          stock: this.handleData.stock ? this.handleData.stock : this.skuSellObj[item].stock,
          giftSkuCode: this.handleData.giftSkuCode ? this.handleData.giftSkuCode : this.skuSellObj[item].giftSkuCode,
          skuBarCode: this.handleData.skuBarCode ? this.handleData.skuBarCode : this.skuSellObj[item].skuBarCode,
          stockStatus: true,
          giftSkuCostPriceStatus: true,
          giftSkuId: this.skuSellObj[item].giftSkuId,
          stockAlter: 0,
          stockType: 0
        };
      }
      this.handleData.giftSkuCode = '';
    },
    handleBarCode(){
      for (let item in this.skuSellObj) {
        this.skuSellObj[item] = {
          giftSkuCostPrice: this.handleData.giftSkuCostPrice ? this.handleData.giftSkuCostPrice : this.skuSellObj[item].giftSkuCostPrice,
          stock: this.handleData.stock ? this.handleData.stock : this.skuSellObj[item].stock,
          giftSkuCode: this.handleData.giftSkuCode ? this.handleData.giftSkuCode : this.skuSellObj[item].giftSkuCode,
          skuBarCode: this.handleData.skuBarCode ? this.handleData.skuBarCode : this.skuSellObj[item].skuBarCode,
          stockStatus: true,
          giftSkuCostPriceStatus: true,
          giftSkuId: this.skuSellObj[item].giftSkuId,
          stockAlter: 0,
          stockType: 0
        };
      }
      this.handleData.skuBarCode = '';
    },
    handleSpuStock() {
      // this.goodsForm.spuList[0].stock = 0;
      this.goodsForm.stock = 0;
      for (let item in this.skuSellObj) {
        if (!this.skuSellObj[item].stock) {
          // this.goodsForm.spuList[0].stock = Number(this.goodsForm.spuList[0].stock) + 0;
          this.goodsForm.stock = Number(this.goodsForm.stock) + 0;
        } else {
          // this.goodsForm.spuList[0].stock = Number(this.goodsForm.spuList[0].stock) + Number(this.skuSellObj[item].stock);
          this.goodsForm.stock = Number(this.goodsForm.stock) + Number(this.skuSellObj[item].stock);
        }
        // this.goodsForm.spuList[0].costPrice = this.skuSellObj[item].giftSkuCostPrice;
        // this.goodsForm.costPrice = this.skuSellObj[item].giftSkuCostPrice;
      }
    },
    // 获取sku数据
    getSkuList() {
      let goodsStandardInfoCopy = deepClone(this.goodsStandardInfo);
      let arr = [];
      this.skuCols = [];
      /** ****组合sku的数据*****/
      for (let item of goodsStandardInfoCopy) {
        for (let i of item.valueList) {
          i.specStandardName = item.specName;
          i.specStandardId = item.specId;
        }
        this.skuCols.push(item.specName);
        arr.push(item.valueList);
      }

      let arrCopy = this.combine(deepClone(arr));
      let goodsSkuList = [];
      for (let i = 0; i < arrCopy.length; i++) {
        goodsSkuList.push({
          data: arrCopy[i],
          cols: [],
          id: [],
          mapId: ''
        });
        for (let j = 0; j < arrCopy[i].length; j++) {
          goodsSkuList[i].cols.push(arrCopy[i][j].specStandardValueName);
          goodsSkuList[i].id.push(arrCopy[i][j].specStandardValueId);
        }
        goodsSkuList[i].mapId = goodsSkuList[i].id.join('_');
      }
      this.goodsSkuList = deepClone(goodsSkuList);
      /** ****获取合并单元格的数组值start *****/
      let numArr = [];
      this.stValCount = [];
      for (let k = 0; k < goodsStandardInfoCopy.length; k++) {
        if (goodsStandardInfoCopy[k].valueList.length > 0) {
          numArr[k] = goodsStandardInfoCopy[k].valueList.length;
        }
      }
      let num = 1;
      for (let m = 0; m < numArr.length; m++) {
        num = num * numArr[m];
        this.stValCount[m] = num;
      }
      /** ****获取合并单元格的数组值 this.stValCount   end *****/

      // 组合sku的销售值信息 价格，库存，sku编码 ，商品条形码
      let goodsSkuListCopy = deepClone(goodsSkuList);
      let skuSellObjCopy = deepClone(this.skuSellObj);
      this.skuSellObj = {};

      for (let item of goodsSkuListCopy) {
        if (skuSellObjCopy[item.mapId]) {
          this.skuSellObj[item.mapId] = {
            giftSkuCostPrice: (Object.keys(skuSellObjCopy).length > 0 && skuSellObjCopy[item.mapId].giftSkuCostPrice) ? Number(skuSellObjCopy[item.mapId].giftSkuCostPrice).toFixed(2) : '',
            stock: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].stock : '',
            giftSkuCode: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].giftSkuCode : '',
            skuBarCode: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].skuBarCode : '',
            giftSkuId: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].giftSkuId : '',
            stockStatus: true,
            giftSkuCostPriceStatus: true,
            stockAlter: 0,
            stockType: 0
            // skuId: Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].skuId : ''
          };
          this.stockObj[item.mapId] = Object.keys(skuSellObjCopy).length > 0 ? skuSellObjCopy[item.mapId].stock : '';
        } else {
          this.skuSellObj[item.mapId] = {
            giftSkuCostPrice: '',
            stock: undefined,
            giftSkuCode: '',
            skuBarCode: '',
            stockStatus: true,
            giftSkuCostPriceStatus: true,
            giftSkuId: '',
            stockAlter: 0,
            stockType: 0
            // skuId: ''
          };
        }
      }
      this.skuSellObj = deepClone(this.skuSellObj);
      this.skuSellObj2 = deepClone(this.skuSellObj);
      this.refash = !this.refash;
    },
    combine(arr) {
      arr.reverse();
      let r = [];

      (function f(t, a, n) {
        if (n == 0) return r.push(t);
        for (let i = 0; i < a[n - 1].length; i++) {
          f(t.concat(a[n - 1][i]), a, n - 1);
        }
      })([], arr, arr.length);
      // var t = r;
      return r; // r是排列组合后的数据与
    },
    /*          规格相关 end         */
    handleValiedSkuCode(value, key, num) {
      let regExp = /^[a-zA-Z0-9\-\—]{1,32}$/;
      if (value) {
        if (!regExp.test(value)) {
          this.$message.error('sku编码只能是数字或字母或-且最多32个字符');
          if (num === 1) {
            this.handleData.giftSkuCode = '';
          } else if (num === 2) {
            this.skuSellObj[key].giftSkuCode = '';
          }
        }
      }
    },
    handleValiedskuBarCode(value, key, num) {
      let regExp = /^[a-zA-Z0-9]{1,32}$/;
      if (value) {
        if (!regExp.test(value)) {
          this.$message.error('条形码只能是数字或字母且最多32个字符');
          if (num === 1) {
            this.handleData.skuBarCode = '';
          } else if (num === 2) {
            this.skuSellObj[key].skuBarCode = '';
          }
        }
      }
    },
    // 成本价
    handleValidIntegral(value, key, num) {
      if(value){
        const regExp = /[\u4e00-\u9fa5]/g;
        if(regExp.test(value)) {
          this.skuSellObj[key].giftSkuCostPrice = '';
          this.$message.error('成本只能是数字');
        }
      }
      if (!value && value !== 0) {
        this.skuSellObj[key].giftSkuCostPriceStatus = false;
        this.$message.error('成本价是必填项');
      } else if (value < 0) {
        this.skuSellObj[key].giftSkuCostPriceStatus = false;
        this.$message.error('成本价必须大于0');
      } else {
        this.skuSellObj[key].giftSkuCostPriceStatus = true;
      }
      let arr1 = Object.keys(this.skuSellObj);
      if(arr1.length > 1){
        let arr2 = [];
        for(let key1 in this.skuSellObj){
          arr2.push(this.skuSellObj[key1].giftSkuCostPrice);
        }
        let max = Math.max.apply(null, arr2);
        let min = Math.min.apply(null, arr2);
        if(max === min){
          this.goodsForm.costPrice = min;
          // this.goodsForm.spuList[0].costPrice = min;
        }else{
          // this.goodsForm.spuList[0].costPrice = min + '~' + max;
          this.goodsForm.costPrice = min + '~' + max;
        }
      }else if(arr1.length === 1){
        this.goodsForm.costPrice = this.skuSellObj[key].giftSkuCostPrice;
        // this.goodsForm.spuList[0].costPrice = this.skuSellObj[0].giftSkuCostPrice;
      }
    },
    // 库存
    handleValidStock(value, key, num) {
      this.goodsForm.spuList[0].stock = 0;
      this.goodsForm.stock = 0;
      if (!value && value !== 0) {
        this.skuSellObj[key].stockStatus = false;
        this.$message.error('库存是必填项');
      } else {
        this.skuSellObj[key].stockStatus = true;
      }
      if(this.isEdit){
        if(Number(this.stockObj[key]) > Number(this.skuSellObj[key].stock)){
          this.skuSellObj[key].stockType = 0;
          this.skuSellObj[key].stockAlter = Number(this.stockObj[key]) - Number(this.skuSellObj[key].stock);
        }else{
          this.skuSellObj[key].stockType = 1;
          this.skuSellObj[key].stockAlter = Number(this.skuSellObj[key].stock) - Number(this.stockObj[key]);
        }
        if(!this.stockObj[key]){
          this.skuSellObj[key].stockType = 1;
          this.skuSellObj[key].stockAlter = this.skuSellObj[key].stock;
        }
      }
      let arr1 = Object.keys(this.skuSellObj);
      if(arr1.length > 1){
        // let arr2 = [];
        for(let key1 in this.skuSellObj){
          // arr2.push(this.skuSellObj[key1].giftSkuCostPrice);
          this.goodsForm.stock = Number(this.goodsForm.stock) + Number(this.skuSellObj[key1].stock);
        }
      }else if(arr1.length === 1){
        this.goodsForm.stock = this.skuSellObj[key].stock;
      }
      this.handleValidIntegral(value, key, num);
    },
    // 保存
    submitForm(goodsForm) {
      if(this.btnLoading) return;
      if (this.goodsStandardInfo.length > 0) {
        for (let item of this.goodsStandardInfo) {
          if (item.specId == '') {
            this.$message.error('请选择规格');
            return false;
          }
          if (
            !item.valueList.every(cols => {
              return cols.specStandardValueId !== '';
            })
          ) {
            this.$message.error('请选择规格值');
            return false;
          }
        }
      }
      if (this.image.length === 0) {
        this.$message.error('请上传主图');
        return false;
      }
      // if(!this.goodsForm.operAuthType){
      //   this.$message.error('请选择操作人权限');
      //   return false;
      // }
      if(!this.$refs.accg.validate()) return;
      this.$refs.accg.save();
      this.$refs[goodsForm].validate(valid => {
        if (!valid){
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        }else{
          // 处理sku销售数据
          let skuList = [];
          if (this.goodsStandardInfo.length > 0) {
            for (let item in this.skuSellObj) {
              let goodsStandard = this.goodsSkuList.find(i => {
                return i.mapId === item;
              }).data;

              goodsStandard = goodsStandard.map(item => {
                // delete item.remark;
                delete item.propImg;
                return item;
              });
              skuList.push({
                giftId: this.giftId,
                giftSkuId: this.skuSellObj[item].giftSkuId,
                stock: this.skuSellObj[item].stock,
                giftSkuCode: this.skuSellObj[item].giftSkuCode,
                skuBarCode: this.skuSellObj[item].skuBarCode,
                giftSkuCostPrice: this.skuSellObj[item].giftSkuCostPrice,
                giftSkuStrand: JSON.stringify(goodsStandard),
                stockType: this.skuSellObj[item].stockType,
                stockAlter: this.skuSellObj[item].stockAlter,
              });
            }

            if (this.isStdImg) {
              // 存在规格图片
              this.goodsStandardInfo[0].standardimg = 2;
            } else {
              this.goodsStandardInfo[0].standardimg = 1;
              for (let i of this.goodsStandardInfo[0].valueList) {
                i.propImg = '';
              }
            }
            if (this.isStdImg) {
              // 规格图必须上传
              if (this.goodsStandardInfo[0]) {
                for (let item of this.goodsStandardInfo[0].valueList) {
                  if (item.propImg === '' || !item.propImg) {
                    this.$message.error('请上传规格图片');
                    return false;
                  }
                }
              }
            }
            for (let item in this.skuSellObj) {
              if (!this.skuSellObj[item].giftSkuCostPrice && this.skuSellObj[item].giftSkuCostPrice !== 0) {
                this.$message.error('请完善规格成本价信息');
                return false;
              } else if (!this.skuSellObj[item].stock && this.skuSellObj[item].stock !== 0) {
                this.$message.error('请完善规格库存信息');
                return false;
              }
              if (!this.skuSellObj[item].giftSkuCostPriceStatus || !this.skuSellObj[item].stockStatus) {
                this.$message.error('请填写正确格式的sku信息');
                return false;
              }
            }
          } else {
            skuList = [];
          }
          // this.btnLoading = true;
          this.$emit('updateLoading');
          let params = {
            giftId: this.giftId,
            giftType: 1, // 实物礼品
            // shopId: '', // 门店id
            giftName: this.goodsForm.giftName, // 礼品名称
            marketPrice: this.goodsForm.marketPrice, // 市场价
            costPrice: this.goodsStandardInfo.length == 0 ? this.goodsForm.costPrice : -1, // 成本价
            stock: this.goodsForm.stock, // 库存
            giftNo: this.goodsForm.giftNo, // 礼品编码
            giftBarNo: this.goodsForm.giftBarNo, // 礼品条形码
            giftImages: this.goodsForm.giftImages, // 礼品主图
            giftDescrption: this.goodsForm.giftDescrption, // 礼品详情
            refundFlag: this.goodsForm.refundFlag, // 是否支持退货
            giftSpecInfo: this.goodsStandardInfo.length > 0 ? JSON.stringify(this.goodsStandardInfo) : '',
            skuList: skuList,
            // operAuthType: this.goodsForm.operAuthType, // 操作人权限
            // operAuth: this.goodsForm.operAuthPre.join(','), // 操作人权限
            operAuthType: 1, // 操作人权限
            operAuth: '', // 操作人权限
            deliveryType: this.goodsForm.deliveryType, // 兑换方式
            source: 1, // 新建方式 默认手动发布1
            shopSelectType: this.diliveryData.shopSelectType, // 门店选择类型
            // shopImportUuid: this.diliveryData.shopImportUuid, // 导入门店唯一标识 仅用于新增
            shopCodeList: this.diliveryData.shopCodeList, // 门店CodeList
            stockUseType: this.goodsForm.stockUseType, // 库存使用类型
          };
          this.btnLoading = true;
          console.log(params);
          if (this.isEdit) {
            // params.giftId = this.giftId;
            giftUpdate(params).then(res =>{
              if (res.code === '0000') {
                this.$router.push({ path: '/gift-manage/real-gift' });
                this.btnLoading = false;
              } else {
                this.btnLoading = false;
                this.$message.error(res.message);
              }
            }).finally(() => this.$emit('updateLoading', false));
          }else{
            // params.giftId = '';
            giftSave(params).then(res =>{
              if (res.code === '0000') {
                this.$store.commit('updateShowCornerCanUseApp', true);
                this.$router.push({ path: '/gift-manage/real-gift' });
                this.btnLoading = false;
              } else {
                this.btnLoading = false;
                this.$message.error(res.message);
              }
              let callbackId = this.$route.query.callbackId;
              if(callbackId) {
                let obj = JSON.parse(localStorage.getItem('welfareCreateCallback') || '{}');
                obj[callbackId] = true;
                localStorage.setItem('welfareCreateCallback', JSON.stringify(obj));
              }
            }).finally(() => this.$emit('updateLoading', false));
          }
        }
      });
    }
  },
};
</script>
<style lang="less" scoped>
.dash-style{
  border-bottom: 1px dashed #2f54eb;
}
.w-630 {
  width: 630px;
}
.w-480 {
  width: 480px;
}
.w-350 {
  width: 350px;
}
.w-900 {
  width: 900px;
}
.mb56 {
  margin-bottom: 56px;
}
.ml8{
  margin-left: 8px;
}
.add-sku-content{
  border: 1px solid #E4E7ED;
  .add-sku{
    margin: 10px 13px;
    padding-top: 12px;
    padding-left: 12px;
    padding-bottom: 12px;
    background: #F7F8FA;
    .add-sku-button{
      width: 110px;
      height: 32px;
      background: #FFFFFF;
      border-radius: 2px;
      border: 1px dashed #C4C6CF;
      text-align: center;
    }
  }
}
.from-content {
  position: relative;
  .demo-ruleForm {
    .form-section {
      padding: 30px 20px;
      h3 {
        color: #303133;
        font-size: 14px;
        font-weight: 700;
        margin-bottom: 31px;
        // margin-left: 20px;
        padding-bottom: 9px;
        border-bottom: 1px solid #dfdfdf;
      }
      h3::before{
        clear: both;
        content: "";
        display: inline-block;
        // height: 0;
        overflow: hidden;
        width: 3px;
        height: 12px;
        line-height: 14px;
        margin-right: 8px;
        background: #2F54EB;
      }
      .tip-warm {
        color: #909399;
        font-size: 12px;
        i {
          color: #faad14;
          margin-right: 5px;
        }
      }
      .standard-info {
        //规格信息
        .add-sku-list {
          margin: 10px 13px 10px 13px;
          .add-sku-item {
            width: 100%;
            .sku-name {
              padding: 8px;
              background: #f3f6f9;
              position: relative;
              .sku-title {
                color: #303133;
                margin-right: 7px;
              }
              .sku-value-title {
                color: #303133;
                width: 55px;
              }
              .delete-btn {
                color: #909399;
                font-size: 14px;
                position: absolute;
                right: 20px;
                cursor: pointer;
                &:hover {
                  color: #2f54ed;
                }
              }
            }
            .value-content {
              padding: 15px 8px 15px 8px;
              display: flex;
              .sku-value-title {
                color: #303133;
                width: 55px;
              }
              .value-list {
                display: inline-block;
                flex: 1;

                .value-item {
                  display: inline-block;
                  margin-right: 10px;
                  position: relative;
                  .el-icon-error {
                    font-size: 16px;
                    position: absolute;
                    right: -7px;
                    top: -7px;
                    color: #c0c4cc;
                    display: none;
                    cursor: pointer;
                  }
                  &:hover .el-icon-error {
                    display: inline-block;
                    color: #909399;
                  }
                }
                .emptyValueList{
                  font-size: 12px;
                  color: rgb(144, 147, 153);
                }
                .hasValueList{
                  font-size: 12px;
                  color: rgb(144, 147, 153);
                  margin-top: 129px;
                }
              }
            }
          }
        }
      }
      .sku-table-content {
        padding: 10px;
        width: 900px;
        border: 1px solid #dcdfe6;
        border-radius: 2px;
        .batch-box {
          padding-left: 130px;
          font-size: 0;
          height: 40px;
        }
      }
    }
    .fixed-btn {
      width: 100%;
      height: 56px;
      position: fixed;
      bottom: 0px;
      left: 200px;
      background: #fff;
      border-top: 1px solid #e4e7ed;
      text-align: center;
      margin-left: -100px;
      z-index: 2;
      font-size: 0px;
      .el-button {
        margin-top: 12px;
      }
    }
  }

  .anchor-link {
    width: 120px;
    position: fixed;
    right: 24px;
    top: 180px;
    background: #fff;
    .link-item {
      height: 24px;
      line-height: 24px;
      color: #606266;
      font-size: 12px;
      border-left: 2px solid #ebeef5;
      padding-left: 18px;
      cursor: pointer;
    }
  }
}
.undeline-dash{
  border-bottom: 1px dashed #2F54EB;
  font-weight:500;
}
.from-content .see-btn {
  color: #909399;
  margin-left: 15px;
}
.from-content .see-btn:hover {
  color: #2f54ed;
}
.ml20 {
  margin-left: 20px;
}
.mr10 {
  margin-right: 10px;
}
.mr16 {
  margin-right: 16px;
}
.table-img {
  cursor: pointer;
  position: absolute;
  top: 44px;
  left: 0;
  width: 90px;
  height: 90px;
  background: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  .avatar-uploader{
    z-index: 2;
    text-align: center;
    .avatar-uploader-icon{
      margin-top: 30px;
      color: #909399;
    }
  }
  .triangle{
    position:absolute;
    top: -6px;
    left: 36px;
    width: 0;
    height: 0;
    border-width: 0 6.5px 6px;
    border-style: solid;
    border-color: transparent transparent #dcdfe6;
  }
  .triangle:after{
    content: "";
    position: absolute;
    top: 2px;
    left: -4.5px;
    border-width: 0 4.5px 4px;
    border-style: solid;
    border-color: transparent transparent #fff;
  }
}
.table-img img {
  width: 88px;
  height: 88px;
  border-radius: 4px;
}
// .table-img:hover {
//   border: 1px dashed #2f54ed;
//   .triangle{
//     border-color: transparent transparent #2f54ed;
//   }
// }
.img-modal {
  width: 89px;
  height: 89px;
  position: absolute;
  left: -1px;
  top: -1px;
  background: rgba(0, 0, 0, 0.5);
  display: none;
  cursor: pointer;
  border-radius: 4px;
  text-align: center;
}
.img-modal .el-icon-delete {
  color: #fff;
  margin-top: 42px;
}
.table-img:hover .img-modal {
  display: inline-block;
}
.tips-content {
  position: absolute;
  left: -4px;
  top: 8px;
}
.store-tips {
  width: 200px;
  position: absolute;
  left: -10px;
}
/* 规格值 */
</style>
<style>
.add-sku-button .el-button--text{
  color: #303133;
}
.sku-table th.star div::before {
  content: '*';
  color: red;
}
.right-border {
  border-right: 1px solid #ebeef5;
}
.sku-table-content .sku-table th {
  line-height: 17px !important;
}
.hidden-limit .dm-input__counter{
  display: none;
}
.batch-style{
  border-radius: 4px;
  padding: 5px !important;
}
.popver-button .el-button{
  min-width: auto !important;
  vertical-align: top;
  line-height: 22px;
  padding: 0 5px;
  font-size: 12px;
}
.popver-button .el-button.cancel-style:focus, .el-button.cancel-style:hover {
  color: #2f54eb !important;
  border-color: #2f54eb !important;
  background-color: #fff !important;
}
</style>
