<template>
  <div class="app-container">
    <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
      <el-card class="box-card">
        <h3>商品主信息</h3>

        <el-form-item label="商品ID" prop="id">
          <el-input v-model="goods.id" disabled />
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goods.name" placeholder="商城售卖展示名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品简称" prop="reportCategory">
              <el-input v-model="goods.reportCategory" placeholder="加盟商服务工单中展示用" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品编号" prop="goodsSn">
              <el-input v-model="goods.goodsSn" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属分类" prop="categoryId">
              <el-cascader
                style="width:100%"
                v-model="goods.categoryId"
                :options="categoryList"
                expand-trigger="hover"
                clearable
                @change="handleCategoryChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="市场售价" prop="counterPrice">
              <el-input v-model="goods.counterPrice" type="number" placeholder="如果是代金券 这里是抵扣金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品实际售价" prop="retailPrice">
              <el-input v-model="goods.retailPrice" type="number" placeholder="客户实际需要支付的金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="活动时间">
              <el-date-picker v-model="activityArray" type="datetimerange" style="width:100%" class="filter-item"
                range-separator="至" value-format="yyyy-MM-dd HH:mm:ss" start-placeholder="活动开始日期" end-placeholder="活动结束日期"
                :picker-options="{}" />
            </el-form-item>
          </el-col>-->
          <el-col :span="6">
            <el-form-item label="计提金额" required>
              <el-input v-model="goods.serviceFee" type="number" placeholder="请输入服务人员最大可计提金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上线城市" required>
              <!-- <el-cascader style="width:100%" v-model="channelCityValue" placeholder="选择此商品在哪个城市上线"
                :options="channelCitys" :props="{
                    expandTrigger: 'hover',
                    value: 'id',
                    label: 'name',
                    multiple: true,
              }" expand-trigger="hover" clearable />-->

              <div style="display: flex;width:100%;flex-direction: column;">
                <div class="tag-input" style="width:100%" @click="selectCityVisible = true">
                  <template>
                    <el-tag
                      v-for="(unit, unique) in selectedSubmitCity"
                      :key="unit.id"
                      type="info"
                      closable
                    >{{ unit.channel == 5 ? 'wx' : 'dy' }} {{ unit.city }}</el-tag>
                  </template>
                </div>
                <div style="color:#09afff;display: block;">
                  抖音{{ this.selectedSubmitCity.filter(item => item.channel == 26).length }}个城市
                  微信{{ this.selectedSubmitCity.filter(item => item.channel == 5).length }}个城市
                </div>
              </div>
            </el-form-item>
            <div
              style="float: right;font-size: 9px;color: red;display: block;margin-top: -20px;"
              id="myTxt"
            ></div>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存预估数量">
              <el-input v-model="productForm.number" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核销方式" prop="applicableTemplate">
              <el-select
                v-model="goods.applicableTemplate"
                style="width: 100%"
                class="filter-item"
                placeholder="请选择核销模板"
                clearable
              >
                <el-option
                  v-for="item in templates"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="商品类型" prop="type">
              <el-select v-model="goods.type" style="width:100%" placeholder="请选择商品类型">
                <el-option label="服务类(买约一体)" :value="0" />
                <!-- <el-option label="保险类" :value="1" /> -->
                <el-option label="中介类" :value="2" />
                <el-option label="服务类(买约分离)" :value="3" />
                <el-option label="服务补差类" :value="4" />
                <el-option label="代金券" :value="5" />
                <el-option label="实物商品" :value="6" />
                <!-- <el-option label="补差" :value="7" /> -->
              </el-select>
            </el-form-item>
          </el-col>
                   <el-col :span="6" v-if="goods.type ==4">
            <el-form-item label="服务时长" prop="serviceDuration">
              <el-input
                v-model="goods.serviceDuration"
                type="number"
                @change="servieDurationChange"
                placeholder="完成此服务 需要的时长"
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" >
            <el-form-item label="商品属性" prop="attribute" v-if="goods.type === 0 || goods.type == 3">
              <el-select
                v-model="goods.attribute"
                style="width:100%"
                @change="servieDurationChange"
                placeholder="请选择商品属性"
              >
                <el-option label="单次" :value="1" />
                <el-option label="品类" :value="2" />
                <el-option label="周期" :value="3" />
                <el-option label="保姆钟点工" :value="4" />
                <el-option label="收纳" :value="5" />
                <el-option label="其他" :value="6" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="所需技能" prop="serviceSkill">
              <el-select
                v-model="goods.serviceSkill"
                style="width:100%"
                placeholder="完成此项服务，服务人员需要具备的技能"
                clearable
              >
                <el-option
                  v-for="item in skills"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="限购件数" prop="limit">
              <el-input v-model="goods.limit" type="number" placeholder="每个用户最大可购买数，0为不限购"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="goods.type === 0 || goods.type == 3">
          <el-col :span="6">
            <el-form-item label="服务时长" prop="serviceDuration">
              <el-input
                v-model="goods.serviceDuration"
                type="number"
                @change="servieDurationChange"
                placeholder="完成此服务 需要的时长"
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务次数" prop="serviceTimes">
              <el-input v-model="goods.serviceTimes" type="number" placeholder="需要的服务次数">
                <template slot="append">次</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务时段" prop="timeRange">
              <el-select
                v-model="goods.timeRange"
                style="width:100%"
                placeholder="请按顺序选择服务时段"
                multiple
                clearable
              >
                <el-option
                  v-for="item in timerange_s"
                  :key="item.range"
                  :label="item.range"
                  :value="item.range"
                />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="是否热卖" prop="isHot">
              <el-radio-group v-model="goods.isHot">
                <el-radio :label="false">普通</el-radio>
                <el-radio :label="true">热卖</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="上下架" prop="isOnSale" label-width="80px">
              <el-radio-group v-model="goods.isOnSale">
                <el-radio :label="true">上架</el-radio>
                <el-radio :label="false">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否新客专享" prop="isNew" label-width="120px">
              <el-radio-group v-model="goods.isNew">
                <el-radio :label="true">新客专享</el-radio>
                <el-radio :label="false">非新客专享</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否隐藏" prop="isHide">
              <el-radio-group v-model="goods.isHide">
                <el-radio :label="false">可见</el-radio>
                <el-radio :label="true">不可见</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否仅直播间可见(仅抖音渠道有效)" v-model="goods.isOnlyLive">
              <el-radio-group v-model="goods.isOnlyLive">
                <el-radio :label="false">不限制</el-radio>
                <el-radio :label="true">仅直播间</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="goods.type === 0 || goods.type == 3">
          <el-col :span="12">
            <el-form-item label="服务时段范围">
              <el-date-picker
                v-model="timeArray"
                type="daterange"
                style="width:100%"
                class="filter-item"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="{}"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="goods.type === 0 || goods.type == 3">
            <el-form-item label="延迟几小时可约" prop="bookDelayDay">
              <el-input
                v-model="goods.bookDelayDay"
                type="number"
                placeholder="下单时，可以从几小时后开始预约，0或空值以默认值为准（24小时）"
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="显示排序" prop="limit">
              <el-input v-model="goods.sortOrder" type="number" placeholder="数值越小 排列越靠前"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="指定加盟商" prop="assignFraId">
              <el-select
                v-model="goods.assignFraId"
                style="width:100%"
                placeholder="请选择指定加盟商"
                clearable
                filterable
              >
                <el-option
                  v-for="item in fraList"
                  :key="item.id"
                  :label="item.fraName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐商品" prop="recgoodsCategory">
              <el-cascader
                v-model="recgoodsCategory"
                :options="goodsList"
                expand-trigger="hover"
                :props="{ expandTrigger: 'hover', value: 'value', label: 'label', multiple: true }"
                style="width:100%"
                clearable
                @change="handleTypeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
             <el-col :span="12" v-if="goods.type==4">
            <el-form-item label="关联商品" prop="goodsSupplement">
              <el-cascader
                v-model="goodsSupplement"
                :options="goodsList"
                expand-trigger="hover"
                :props="{ expandTrigger: 'hover', value: 'value', label: 'label', multiple: true }"
                style="width:100%"
                clearable
                @change="handleTypeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <!-- <el-card class="box-card">
        <h3>商品规格</h3>
        <el-row :gutter="20" type="flex" align="middle" style="padding:20px 0;">
          <el-col :span="10">
            <el-button :plain="true" type="primary" @click="handleSpecificationShow({}, 0)">添加</el-button>
          </el-col>
        </el-row>
        <el-table :data="specifications">
          <el-table-column property="specification" label="规格名称" />

          <el-table-column property="picUrl" label="规格图片">
            <template slot-scope="scope">
              <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40" />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleSpecificationShow(scope.row, 1)"
              >设置</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog :visible.sync="specVisiable" title="设置规格">
          <el-form
            ref="specForm"
            :rules="rules"
            :model="specForm"
            status-icon
            label-position="left"
            label-width="100px"
            style="width: 400px; margin-left:50px;"
          >
            <el-form-item label="规格名称" prop="specification">
              <el-input v-model="specForm.specification" />
            </el-form-item>

            <el-form-item label="规格图片" prop="picUrl">
              <el-upload
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadSpecPicUrl"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="specVisiable = false">取消</el-button>
            <el-button type="primary" v-if="specType == 1" @click="handleSpecificationEdit">确定修改</el-button>
            <el-button type="primary" v-if="specType != 1" @click="handleSpecificationAdd">确定</el-button>
          </div>
        </el-dialog>
      </el-card> -->
      <el-card class="box-card">
        <h3>规格类型设置</h3>
       <el-row>
        <el-form-item label="规格类型" prop="sku">
          <el-radio-group v-model="goods.productType">
            <el-radio :label="1" :disabled="true">单规格无加购</el-radio>
            <el-radio :label="2" :disabled="true">多规格</el-radio>
            <el-radio :label="3" v-if="goods.type!=4" :disabled="true">加购</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <!-- v-if="goods.productType==3&&goods.type!=4" -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="加购名称">
            <el-input
              v-model="goods.unitDescribe"
              :disabled="goods.type==4"
              placeholder="如（新居开荒无限加购）"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="加购单位">
            <el-input v-model="goods.unitArea" :disabled="goods.type==4" placeholder="如（1㎡、台等）" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="展示单价">
            <el-input v-model="goods.unitPrice" :disabled="goods.type==4" type="number">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
         <el-col :span="6" v-if="!(goods.type==4)">
            <el-form-item label="最多加购数量">
              <el-input v-model="goods.unitMaximum" :disabled="goods.type==4" type="number">

              </el-input>
            </el-form-item>
          </el-col>
      </el-row>
      <el-row v-if="goods.type==4">
        <el-col :span="6">
            <el-form-item label="最多加购数量">
              <el-input v-model="goods.unitMaximum"  type="number">

              </el-input>
            </el-form-item>
          </el-col>
      </el-row>
       <div style="margin:0 0 20px 64px;">
        <el-button :plain="true" type="primary" @click="handleProductShow({},-1)" size="mini" v-if="goods.productType==2">添加规格</el-button>
        <el-button :plain="true" type="primary" @click="handleProductShow({},-1)" size="mini" v-if="goods.productType==3&&goods.type!=4">加购设置</el-button>
      </div>
        <el-table :data="products" border>
           <!-- v-if="goods.productType!=3" -->
          <el-table-column property="value" label="货品规格">
            <template slot-scope="scope">
              <!-- <el-tag v-for="tag in scope.row.specifications" :key="tag">{{ tag }}</el-tag> -->
               {{ scope.row.specifications[0] }}
            </template>
          </el-table-column>
            <el-table-column property="unitIncreaseNumber"  label="加购数量"  v-if="goods.productType==3" :key="Math.random()"/>
          <el-table-column property="price" width="100" label="实际售卖价" :key="Math.random()"/>
          <el-table-column property="counterPrice" width="100" label="市场售价" :key="Math.random()"/>
          <el-table-column property="number" label="货品数量" :key="Math.random()"/>
          <el-table-column property="salesNumber"  label="已售库存" :key="Math.random()"/>
          <!-- <el-table-column property="salesNumber" width="100" label="已售库存" /> -->
          <el-table-column property="serviceTimes" label="服务次数"  :key="Math.random()"/>
          <el-table-column property="serviceDuration" label="服务时长"    :key="Math.random()"/>
          <el-table-column property="timeRange" label="服务时段"   :key="Math.random()">
            <template slot-scope="scope">
              <div v-for="(item, index) in scope.row.timeRange" :key="index">{{ item }}</div>
            </template>
          </el-table-column>
          <el-table-column property="url" label="货品图片" :key="Math.random()" v-if="goods.productType!=3">
            <template slot-scope="scope">
              <img v-if="scope.row.url" :src="scope.row.url" width="40" />
            </template>
          </el-table-column>
             <el-table-column property="serviceDuration" label="是否显示"    :key="Math.random()">
             <template slot-scope="scope">
               {{scope.row.deleted?'否':'是'}}
             </template>

             </el-table-column>

          <el-table-column
            align="center"
            label="操作"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleProductShow(scope.row,scope.$index)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog :visible.sync="productVisiable" title="编辑货品">
          <el-form
            ref="productForm"
            :model="productForm"
            :rules="productRules"
            status-icon
            label-position="left"
            label-width="100px"
            style="width: 400px; margin-left:50px;"
          >
            <!-- <el-form-item label="货品规格" prop="specifications">
              <el-tag>{{ productForm.specifications[0] }}</el-tag>
            </el-form-item> -->
            <!-- v-if="goods.productType!=3" -->
                    <el-form-item label="规格名称" prop="specification" >
            <el-input v-model.trim="productForm.specification" />
          </el-form-item>
            <el-form-item label="加购数量" prop="unitIncreaseNumber" v-if="goods.productType==3">
            <el-input v-model="productForm.unitIncreaseNumber" type="number" />
          </el-form-item>
            <el-form-item label="实际售卖价" prop="price">
              <el-input v-model="productForm.price">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="货品数量" prop="number">
              <el-input v-model="productForm.number" />
            </el-form-item>
            <el-form-item label="已售库存" prop="salesNumber">
              <el-input v-model="productForm.salesNumber" type="number" />
            </el-form-item>
            <el-form-item label="市场售价" prop="counterPrice">
              <el-input v-model="productForm.counterPrice" type="number">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="服务次数" prop="serviceTimes"  v-if="goods.productType!=3">
              <el-input v-model="productForm.serviceTimes" type="number">
                <template slot="append">次</template>
              </el-input>
            </el-form-item>
            <el-form-item label="服务时长" prop="serviceDuration"  >
              <el-input
                v-model="productForm.serviceDuration"
                type="number"
                @change="servieDurationChangeP"
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
            <el-form-item label="服务时段" prop="timeRange"  v-if="goods.type != 4&&goods.type != 2&&goods.productType!=3">
              <el-select
                v-model="productForm.timeRange"
                placeholder="请按顺序选择服务时段"
                multiple
                clearable
              >
                <el-option
                  v-for="item in timerange_p"
                  :key="item.range"
                  :label="item.range"
                  :value="item.range"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="是否显示" prop="deleted">
              <el-radio-group v-model="productForm.deleted">
                <el-radio :label="false">是</el-radio>
                <el-radio :label="true">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="货品图片" prop="url"  v-if="goods.productType!=3">
              <el-upload
                :headers="headers"
                :action="uploadPath"
                :show-file-list="false"
                :on-success="uploadProductUrl"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="productForm.url" :src="productForm.url" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="productVisiable = false">取消</el-button>
            <el-button type="primary" @click="handleProductEdit">确定</el-button>
          </div>
        </el-dialog>
      </el-card>


      <el-card class="box-card">
        <h3>商品图片</h3>
        <el-row>
          <el-col :span="6">
            <el-form-item label="商品图片" prop="picUrl">
              <el-upload
                :action="uploadPath"
                :show-file-list="false"
                :headers="headers"
                :on-success="uploadPicUrl"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="goods.picUrl" :src="goods.picUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <span class="info">建议尺寸 430*430 商品列表页使用</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分享微信图片" prop="shareWxUrl">
              <el-upload
                :action="uploadPath"
                :show-file-list="false"
                :headers="headers"
                :on-success="uploadShareWxPicUrl"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="goods.shareWxUrl" :src="goods.shareWxUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <span class="info">比例5:4</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分享海报图片" prop="shareUrl">
              <el-upload
                :action="uploadPath"
                :show-file-list="false"
                :headers="headers"
                :on-success="uploadSharePicUrl"
                class="avatar-uploader"
                accept=".jpg, .jpeg, .png, .gif"
              >
                <img v-if="goods.shareUrl" :src="goods.shareUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
              <span class="info">固定尺寸 750*1375</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分享文案" prop="shareAds">
              <el-input v-model="goods.shareAds" rows="6" type="textarea" placeholder="分享文案"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="adv-img">
          <el-form-item label="宣传画廊">
            <el-upload
              :action="uploadPath"
              :headers="headers"
              :limit="5"
              :file-list="galleryFileList"
              :on-exceed="uploadOverrun"
              :on-success="handleGalleryUrl"
              :on-remove="handleRemove"
              multiple
              accept=".jpg, .jpeg, .png, .gif"
              list-type="picture-card"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <span class="info">建议尺寸 750*492 ，第一张图片为首页商品展示图</span>
          </el-form-item>
        </div>

        <!-- <el-form-item label="商品单位">
          <el-select v-model="goods.unit" clearable>
            <el-option v-for="item in units" :key="item.unit" :label="item.label" :value="item.unit" />
          </el-select>
        </el-form-item>-->

        <el-form :rules="rules" :model="productForm" label-width="150px">
          <!--<el-row>
            <el-col :span="12">
              <el-form-item label="推广奖励方式" prop="disType">
                <el-radio-group v-model="productForm.disType">
                  <el-radio :label="0">无奖励</el-radio>
                  <el-radio :label="1">实收金额百分比</el-radio>
                  <el-radio :label="2">固定奖励金额</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-show="productForm.disType == 1" label="奖励百分比" prop="disPercent">
                <el-input v-model="productForm.disPercent" type="number" maxlength="2">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>

              <el-form-item v-show="productForm.disType == 2" label="固定奖励金额" prop="disAmount">
                <el-input v-model="productForm.disAmount" type="number">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="指定加盟商" prop="assignFraId">
                <el-select v-model="goods.assignFraId" style="width:100%" placeholder="请选择指定加盟商" clearable filterable>
                  <el-option v-for="item in fraList" :key="item.id" :label="item.fraName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>-->
        </el-form>

        <el-form-item label="关键字">
          <el-tag
            v-for="tag in keywords"
            :key="tag"
            closable
            type="primary"
            @close="handleClose(tag)"
          >{{ tag }}</el-tag>
          <el-input
            v-if="newKeywordVisible"
            ref="newKeywordInput"
            v-model="newKeyword"
            class="input-new-keyword"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-keyword" type="primary" @click="showInput">+ 增加</el-button>
        </el-form-item>

        <!--  <el-row>
        <el-col :span="12">
            <el-form-item label="所属分类">
              <el-cascader style="width:100%" v-model="categoryIds" :options="categoryList" clearable
                props.expandTrigger="hover" @change="handleCategoryChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属统计分类" prop="sCategoryId">
              <el-cascader style="width:100%" v-model="sCategoryId" :options="sCategory" props.expandTrigger="hover"
                clearable @change="handleSCategoryChange" />
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品简介">
              <el-input v-model="goods.brief" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品复制口令链接">
              <el-input v-model="goods.copyLink" placeholder="商品复制口令链接" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="售卖数量">
              <el-input v-model="goods.sales" placeholder="售卖数量" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务标准">
              <el-input v-model="goods.serviceStandards" placeholder="服务标准" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务须知">
              <el-input v-model="goods.serviceInstructions" placeholder="服务标准" />
            </el-form-item>
          </el-col>
        </el-row>
        <h3>商品详细</h3>
        <el-form-item label>
          <editor v-model="goods.detail" :init="editorInit" />
        </el-form-item>
      </el-card>
    </el-form>

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleEdit">更新商品</el-button>
      <el-button type="info" @click="handleDyPublish">更新并提交抖音审核</el-button>
    </div>
    <div
      style="line-height: 43px;color:red;text-align: center;"
    >暂存为抖音申报版本:将不修改商品信息，知道抖音申请通过后，自动更新为此版本</div>

    <el-dialog :visible.sync="dyFormVisiable" title="抖音申报商品" width="800px">
      <el-form
        ref="dyForm"
        :model="dyForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 600px; margin-left:50px;"
      >
        <el-form-item label="版本号" prop="version" required>
          <el-input v-model.trim="dyForm.version" placeholder="推荐按日期编号 如V20230405" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" required>
          <el-input v-model.trim="dyForm.remark" placeholder="版本描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dyFormVisiable = false">取消</el-button>
        <el-button type="primary" @click="dyPublish">确定</el-button>
      </div>
    </el-dialog>

    <selectCity
      ref="selectCity"
      :visible.sync="selectCityVisible"
      @success="submitSelectCity"
      :selected="selectedSubmitCity"
    />
  </div>
</template>

<script>
import {
  detailGoods,
  editGoods,
  getShop,
  getSkills,
  getStatisticsCategory,
  listCatAndBrand,
  getChannelCitys,
  dyGoods,
  listGoods3
} from "@/api/goods";
import { allChannel } from "@/api/channel";
import { getAllFras } from "@/api/order";
import { allRange } from "@/api/serviceTimeRange";
import { createStorage, uploadPath } from "@/api/storage";
import selectCity from "../goods/selectCity.vue";
import Editor from "@tinymce/tinymce-vue";
import { getToken } from "@/utils/auth";

const typeMap = {
  0: "无奖励",
  1: "实收金额百分比",
  2: "固定奖励金额"
};
export default {
  name: "GoodsEdit",
  components: { Editor, selectCity },
  filters: {
    disTypeFilter(type) {
      return typeMap[type];
    }
  },
  data() {
    var isDuration = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        var number = /^\d+$|^\d+[.]?\d+$/;
        if (!number.test(value) || value <= 0) {
          callback(new Error("请输入服务时长"));
        } else {
          callback();
        }
      }
    };
    var validateTimeRange = (rule, value, callback) => {
      if (
        (this.goods.type === 0 || this.goods.type === 3) &&
        (this.productForm.timeRange == "" ||
          this.productForm.timeRange.length == 0)
      )
        callback(new Error("商品服务时段不能为空"));
      else callback();
    };

    var validateGoodsAttribute = (rule, value, callback) => {
      if (
        (this.goods.type === 0 || this.goods.type === 3) &&
        this.goods.attribute == ""
      )
        callback(new Error("商品属性不能为空"));
      else callback();
    };

    var isNeedSkill = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        if (value == undefined || value == null) {
          callback(new Error("请选择服务所需技能"));
        } else {
          callback();
        }
      }
    };
    var isServiceTimes = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        if (value == undefined || value == null) {
          callback(new Error("请选择所需服务次数"));
        } else {
          callback();
        }
      }
    };
    var activityPriceValidate = (rule, value, callback) => {
      if (this.activityArray.length < 2) {
        callback();
      } else {
        if (value == undefined || value == null || value == "") {
          callback(new Error("请填写活动价格"));
        } else {
          callback();
        }
      }
    };
    return {
       productFormType:'',
      fraList: [],
      selectCityVisible: false,
      channels: [],
      selectedSubmitCity: [], //城市选择控件回传的值
      uploadPath,
      timeArray: [],
      newKeywordVisible: false,
      newKeyword: "",
      keywords: [],
      timerange: [], //时间范围
      timerange_s: [], //跟进服务时间 筛选后的时间范围
      activityArray: [], //限时活动时间
      units: [
        { unit: "3小时" },
        { unit: "2小时" },
        { unit: "1小时" },
        { unit: "次" },
        { unit: "箱" },
        { unit: "罐" },
        { unit: "克" },
        { unit: "升" }
      ], // 规格
      galleryFileList: [],
      sCategory: [], //统计分类 报表时使用
      categoryList: [],
      brandList: [],
      categoryIds: [],
      sCategoryId: [],
      citys: [],
      shops: [],
      skills: [],
      goods: {
        gallery: [],
        shareUrl: "",
        shareWxUrl: "",
        verifyType: "",
        channel: [],
        isOnlyLive: false,
        applicableTemplate: 1,
        assignFraId: "",
        unitDescribe: "",
        unitArea: "",
        unitPrice: "",
          unitMaximum:0,
        productType:1,


      },
       goodsSupplement:[],
      recgoodsCategory: [],

      dyFormVisiable: false,
      dyForm: {
        goodsId: "",
        goodsName: "",
        version: "",
        remark: ""
      },
      specVisiable: false,
      specType: 0,

      specForm: { specification: "", value: "", picUrl: "" },
      multipleSpec: false,

      specifications: [
        { specification: "规格", value: "鲸致标准", picUrl: "" }
      ],
      productVisiable: false,
      productForm: {
          unitIncreaseNumber:1,
        id: 0,
        specification:'',
        specifications: ["鲸致标准"],
        price: 0.0,
        number: 0,
        url: "",
        memberPrice: 0.0,
        counterPrice: 0.0,
        salesNumber: 0,
        serviceTimes: 0,
        serviceDuration: 0,
        deleted: false,
        timeRange: []
      },
      tempIndex:0,
      timerange_p: [], //sku跟进服务时间 筛选后的时间范围
      products:[],
      // products: [
      //   {
      //     unitIncreaseNumber:1,
      //     id: 0,
      //      specification:'',
      //     specifications: ["鲸致标准"],
      //     price: 0.0,
      //     number: 0,
      //     url: "",
      //     disType: 0,
      //     disPercent: 0,
      //     disAmount: 0,
      //     memberPrice: 0,
      //   counterPrice: 0.0,
      //   salesNumber: 0,
      //   serviceTimes: 0,
      //   serviceDuration: 0,
      //   timeRange: []
      //   }
      // ],
      attributeVisiable: false,
      attributeAdd: true,
      attributeForm: { attribute: "", value: "" },
      attributes: [],
      rules: {
        limit: [
          { required: true, message: "限购件数不能为空", trigger: "blur" }
        ],
        goodsSn: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        counterPrice: [
          {
            required: true,
            validator: this.isNumber,
            message: "市场售价不能为空或小于等于0",
            trigger: "blur"
          }
        ],
        categoryId: [
          {
            type: "number",
            required: true,
            message: "请选择商品分类",
            trigger: "change"
          }
        ],
        picUrl: [
          { required: true, message: "商品图片不能为空", trigger: "blur" }
        ],
          specification: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        applicableTemplate: [
          { required: true, message: "请选择核销方式", trigger: "change" }
        ],
        gallery: [
          {
            type: "array",
            required: true,
            message: "宣传栏至少需要一个",
            trigger: "blur"
          }
        ],
        serviceDuration: [
          { validator: isDuration, required: true, trigger: "change" }
        ],
        shops: [{ required: true, message: "所属门店不能为空" }],
        serviceSkill: [
          { validator: isNeedSkill, required: true, trigger: "change" }
        ],
        serviceTimes: [
          { validator: isServiceTimes, required: true, trigger: "blur" }
        ],
        price: [{ required: true, message: "实际售价不能为空" }],
        attribute: [
          {
            validator: validateGoodsAttribute,
            required: true,
            message: "请选择商品属性",
            trigger: "blur"
          }
        ],
        activityPrice: [
          {
            validator: activityPriceValidate,
            required: true,
            message: "活动价不能为空",
            trigger: "blur"
          }
        ],
        // memberPrice: [{ required: true, message: "会员价不能为空" }],
        number: [{ required: true, message: "库存不能为空" }],
        channel: [
          {
            required: true,
            message: "渠道不能为空",
            trigger: "blur",
            type: "array"
          }
        ],
        reportCategory: [
          { required: true, message: "商品简称不能为空", trigger: "blur" }
        ]
      },
      productRules: {
          unitIncreaseNumber: [
          { required: true, message: "加购数量不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "实际售价不能为空", trigger: "blur" }
        ],
        counterPrice: [
          // {
          //   required: true,
          //   validator: this.isNumber,
          //   message: "市场售价不能为空或小于等于0",
          //   trigger: "blur",
          // },
          { required: true, message: "市场售价不能为空", trigger: "blur" }
        ],
        serviceDuration: [
          { validator: isDuration, required: true, trigger: "change" }
        ],
        timeRange: [
          {
            validator: validateTimeRange,
            required: true,
            message: "请选择服务时段",
            trigger: "blur"
          }
        ],
        url: [
          { required: true, message: "商品图片不能为空", trigger: "change" }
        ]
      },
      editorInit: {
        language: "zh_CN",
        height: "400px",
        convert_urls: false,
        plugins: [
          "advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount"
        ],
        toolbar: [
          "searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample",
          "hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen"
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          createStorage(formData)
            .then(res => {
              success(res.data.data.url);
            })
            .catch(() => {
              failure("上传失败，请重新上传");
            });
        }
      },

      templates: [
        { name: "首次服务完成即核销", id: 1 },
        { name: "次卡逻辑 按次核销", id: 2 },
        { name: "代金券", id: 3 },
        { name: "收纳整理", id: 4 }
      ],

      goodsList: [] // 三级商品
    };
  },
  computed: {
    headers() {
      return {
        "X-JZ-Admin-Token": getToken()
      };
    },
    attributesData() {
      var attributesData = [];
      for (var i = 0; i < this.attributes.length; i++) {
        if (this.attributes[i].deleted) {
          continue;
        }
        attributesData.push(this.attributes[i]);
      }
      return attributesData;
    }
  },
  created() {
    this.getChannelCitys();
    this.init();
    this.handleListGoods();
  },
  methods: {
    handleListGoods() {
      listGoods3()
        .then(res => {
          this.goodsList = res.data.data.goodsList;
          // this.categoryList = res.data.data.categoryList;
        })
        .catch(() => {});
    },
    handleTypeChange(value) {
      console.log(value);
    },

    init: function() {
      if (this.$route.query.id == null) {
        return;
      }
      allChannel().then(res => {
        this.channels = res.data.data;
      });
      getAllFras().then(res => {
        this.fraList = res.data.data;
      });

      const goodsId = this.$route.query.id;
      detailGoods(goodsId).then(response => {
        const _goods = response.data.data.goods;
        this.recgoodsCategory = response.data.data.recgoodsCategory;
        if (_goods.type === 4) {
          this.goodsSupplement=response.data.data.goodsSupplement;
        }

        //商品类型
        if (_goods.type == null || typeof _goods.type == "undefined")
          _goods.type = 0;

        if (_goods.shareUrl == null || typeof _goods.shareUrl == "undefined")
          _goods.shareUrl = "";

        if (
          _goods.shareWxUrl == null ||
          typeof _goods.shareWxUrl == "undefined"
        )
          _goods.shareWxUrl = "";

        //如果_goods.channel是null，空
        //_goods.channel = _goods.channel?_goods.channel[0]:null;

        // let shop = this.getShop(_goods.channel);
        // shop.then(res => {
        //   console.log("res--->" + JSON.stringify(res));
        //   this.shops = res.data.data;
        //   //选中门店处理
        //   let shops = [];
        //   console.log("start_goods_shop==>" + _goods.shops);
        //   _goods.shops.forEach(shopId => {
        //     this.shops.forEach(s => {
        //       s.children.forEach(ss => {
        //         if (ss.id == shopId) {
        //           shops.push([s.id, shopId]);
        //         }
        //       })
        //     })
        //   })
        //   console.log("final_goods_shop==>" + shops);
        //   _goods.shops = shops;
        //   document.querySelector('#myTxt').innerHTML = `共选中${_goods.shops.length}家门店`;
        // })

        this.goods = _goods;
        // 稍微调整一下前后端不一致

        if (this.goods.keywords === "") {
          this.goods.keywords = null;
        }
        this.specifications = response.data.data.specifications;
        this.products = response.data.data.products;
        // if (this.products.length > 0) this.productForm = this.products[0];

        this.attributes = response.data.data.attributes;
        this.categoryIds = response.data.data.categoryIds;
        this.sCategoryId = response.data.data.sCategoryIds;
        this.selectedSubmitCity = response.data.data.selectedCitys;

        if (this.goods.bookStartDate)
          this.timeArray = [this.goods.bookStartDate, this.goods.bookEndDate];

        if (this.products[0].activityStart)
          this.activityArray = [
            this.products[0].activityStart,
            this.products[0].activityEnd
          ];

        this.galleryFileList = [];
        for (var i = 0; i < this.goods.gallery.length; i++) {
          this.galleryFileList.push({
            url: this.goods.gallery[i]
          });
        }
        const keywords = response.data.data.goods.keywords;
        if (keywords !== null) {
          this.keywords = keywords.split(",");
        }
        //触发可服务时间端
        //this.servieDurationChange(this.goods.serviceDuration);
      });

      listCatAndBrand().then(response => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      });

      getSkills().then(res => {
        console.info(res);
        this.skills = res.data.data;
      });
      getStatisticsCategory().then(res => {
        this.sCategory = res.data.data;
      });
      this.getTimeRange();
    },
    async getShop(value) {
      console.info({ channelId: value });
      return await getShop({ channelId: value });
    },
    channelChange() {
      let shop = this.getShop(this.goods.channel);
      shop.then(res => {
        console.log("res--->" + JSON.stringify(res));
        this.shops = res.data.data;
      });
    },
    getTimeRange() {
      allRange().then(res => {
        this.timerange = res.data.data;
      });
    },
    handleCategoryChange(value) {
      this.goods.categoryId = value[value.length - 1];
    },
    handleSCategoryChange(value) {
      this.goods.sCategoryId = value[value.length - 1];
    },
    handleCancel: function() {
      this.$router.push({ path: "/goods/list" });
    },
    handleDyPublish() {
      //抖音申报版本
      if (this.goodsValidate()) {
        this.dyFormVisiable = true;
        this.dyForm = {
          version: "",
          remark: "",
          goodsJson: ""
        };
      }
    },
    dyPublish() {
      //抖音版本暂存
      if (this.dyForm.version == "" || this.dyForm.remark == "") {
        this.$message({
          type: "warning",
          message: "请填写版本号和备注内容!"
        });
        return;
      }
      if (!this.goodsValidate()) return;
        let products=[];
      this.products.forEach(pro=>{
        var proItem=pro;
            //proItem.productType=this.goods.productType;
          if(this.goods.productType==2&&pro.specification&&pro.specification!=null){
            proItem.specifications=[pro.specification]
          }
          products.push(proItem);
       });
      const finalGoods = {
        goods: this.goods,
        specifications: this.specifications,
        products: products,
        attributes: this.attributes,
        selectedCitys: this.selectedSubmitCity,
        external: this.dyForm,
        goodsSupplement:this.goodsSupplement
      };
      console.info(finalGoods);

      dyGoods(finalGoods)
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "更新成功"
          });
          this.dyFormVisiable = false;
          this.$router.push({ path: "/douyin/goodsExternalConfig" });
        })
        .catch(response => {
          console.info(response);
          this.$message({
            type: "warning",
            message: response.data.errmsg
          });
        });
    },
    handleEdit: function() {
      if (!this.goodsValidate()) return;
      let goodsParam = JSON.parse(JSON.stringify(this.goods));
      let recGoods = this.recgoodsCategory;
      let list = [];
      recGoods.forEach(item => {
        list.push(item[2]);
      });
      goodsParam.recGoods = list;
  let products=[];
      this.products.forEach(pro=>{
        var proItem=pro;
          //proItem.productType=this.goods.productType;
          if(this.goods.productType==2&&pro.specification&&pro.specification!=null){
            proItem.specifications=[pro.specification]
          }
          products.push(proItem);
       });

      const finalGoods = {
        goods: goodsParam,
        specifications: this.specifications,
        // products: [this.productForm],
        // products: this.products,
        products: products,
        attributes: this.attributes,
        selectedCitys: this.selectedSubmitCity,
        external: this.dyForm,
        goodsSupplement:this.goodsSupplement
      };
      console.info(finalGoods);

      editGoods(finalGoods)
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "更新成功"
          });
          this.$router.push({ path: "/goods/list" });
        })
        .catch(response => {
          this.$message({
            type: "warning",
            message: response.data.errmsg
          });
        });
    },
    goodsValidate() {
      if (this.timeArray && this.timeArray.length === 2) {
        this.goods.bookStartDate = this.timeArray[0];
        this.goods.bookEndDate = this.timeArray[1];
      } else {
        this.goods.bookStartDate = "";
        this.goods.bookEndDate = "";
      }

      if (this.activityArray && this.activityArray.length > 1) {
        this.productForm.activityStart = this.activityArray[0];
        this.productForm.activityEnd = this.activityArray[1];
      } else {
        this.productForm.activityStart = "";
        this.productForm.activityEnd = "";
      }

      if (!this.selectedSubmitCity.length) {
        this.$message({
          type: "提醒",
          message: "请至少选择一个上线城市!"
        });
        return false;
      }

      if (
        this.activityArray.length > 1 &&
        (this.productForm.activityPrice == null ||
          this.productForm.activityPrice == "" ||
          this.productForm.activityPrice == 0)
      ) {
        this.$message({
          type: "提醒",
          message: "请输入活动价格!"
        });
        return false;
      }

      return true;
    },
    servieDurationChange(value) {
      console.info(this.goods.serviceDuration);
      this.goods.timeRange = [];
      this.timerange_s = [];
      this.timerange.forEach(time => {
        if (
          time.duration == this.goods.serviceDuration &&
          time.type == this.goods.attribute
        )
          this.timerange_s.push({ range: time.startTime + "-" + time.endTime });
      });
    },
    servieDurationChangeP(value) {
      console.log(this.productForm.serviceDuration);
      this.productForm.timeRange = [];
      this.timerange_p = [];
      this.timerange.forEach(time => {
        if (
          time.duration == this.productForm.serviceDuration &&
          time.type == this.goods.attribute
        )
          this.timerange_p.push({ range: time.startTime + "-" + time.endTime });
      });
    },
    submitSelectCity(param) {
      console.info(param);
      this.selectedSubmitCity = param.citySelected;
      this.selectCityVisible = false;
    },
    getChannelCitys() {
      getChannelCitys().then(res => {
        this.channelCitys = res.data.data;
      });
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.goods.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick(_ => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.goods.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    },
    uploadPicUrl: function(response) {
      this.goods.picUrl = response.data.url;
    },
    uploadSharePicUrl: function(response) {
      this.goods.shareUrl = response.data.url;
    },
    uploadShareWxPicUrl: function(response) {
      this.goods.shareWxUrl = response.data.url;
    },
    uploadOverrun: function() {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!"
      });
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url);
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url;
        if (file.response === undefined) {
          url = file.url;
        } else {
          url = file.response.data.url;
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1);
        }
      }
    },
    specChanged: function(label) {
      if (label === false) {
        this.specifications = [
          { specification: "规格", value: "标准", picUrl: "" }
        ];
        this.products = [
          {
            id: 0,
            specifications: ["标准"],
            price: 0.0,
            number: 0,
            url: "",
            skuId: "",
            disType: 0,
            disPercent: 0,
            disAmount: 0
          }
        ];
      } else {
        this.specifications = [];
        this.products = [];
      }
    },
    uploadSpecPicUrl: function(response) {
      this.specForm.picUrl = response.data.url;
    },
    handleSpecificationShow(row, type) {
      if (type == 0) {
        this.specForm = { specification: "", value: "", picUrl: "" };
      } else {
        this.specForm = Object.assign({}, row);
      }

      this.specVisiable = true;
      this.specType = type; //1不可编辑
    },
    handleSpecificationAdd() {
      console.log(this.specForm);
      if (
        // this.specForm.value == null ||
        // this.specForm.value == "" ||

        this.specForm.specification == ""
      ) {
        this.$message({
          type: "warning",
          message: "规格名称不能为空"
        });
        return;
      }
      var index = this.specifications.length - 1;

      for (var i = 0; i < this.specifications.length; i++) {
        const v = this.specifications[i];
        if (v.specification === this.specForm.specification) {
          // if (v.value === this.specForm.value) {
          // if (v.value === this.specForm.value) {
          this.$message({
            type: "warning",
            message: "已经存在规格名称:" + v.value
          });
          this.specForm = {};
          this.specVisiable = false;
          return;
          // } else {
          //   index = i;
          // }
        } else {
          index = i;
        }
      }

      this.specifications.splice(index + 1, 0, this.specForm);
      this.specVisiable = false;
      let obj = Object.assign(
        {
          id: "",
          specifications: [this.specForm.specification],
          price: 0.0,
          number: 0,
          url: "",
          memberPrice: 0.0,
          counterPrice: 0.0,
          salesNumber: 0,
          serviceTimes: 0,
          serviceDuration: 0,
          deleted: false,
          timeRange: [],
          currentId: index
        },
        this.specForm
      );
      this.products.push(obj);
      // this.specToProduct(this.specForm);
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        this.products = [];
        return;
      }
      // 根据specifications创建临时规格列表
      var specValues = [];
      var spec = this.specifications[0].specification;
      var values = [];
      values.push(0);

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification;

        if (aspec === spec) {
          values.push(i);
        } else {
          specValues.push(values);
          spec = aspec;
          values = [];
          values.push(i);
        }
      }
      specValues.push(values);

      // 根据临时规格列表生产货品规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0;
      var products = [];
      var combination = [];
      var n = specValues.length;
      for (var s = 0; s < n; s++) {
        combination[s] = 0;
      }
      var index = 0;
      var isContinue = false;
      let that = this;
      do {
        var specifications = [];
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]];
          specifications.push(this.specifications[z].value);
        }

        products[productsIndex] = {
          id: productsIndex,
          specifications: specifications,
          price: 0.0,
          number: 0,
          url: "",
          disType: 0
        };
        productsIndex++;

        index++;
        combination[n - 1] = index;

        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0;
            index = 0;
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1;
            }
          }
        }
        isContinue = false;
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true;
          }
        }
      } while (isContinue);

      this.products = products;
    },
    specToProduct(row) {
      let obj = Object.assign(
        {
          id: "",
          specifications: [row.specification],
          price: 0.0,
          number: 0,
          url: "",
          disType: 0
        },
        row
      );
      this.products.push(obj);
    },
    handleSpecificationEdit() {
      this.specForm.updateTime = "";
      for (var i = 0; i < this.specifications.length; i++) {
        const v = this.specifications[i];
        if (v.id === this.specForm.id) {
          this.specifications.splice(i, 1, this.specForm);
          this.products[i].specifications = [this.specForm.specification];
          break;
        }
      }
      this.specVisiable = false;
    },
    handleProductShow(row,type) {
      // this.productForm = Object.assign({}, row);
      this.productVisiable = true;
      if(type==-1){
        this.productFormType='create';
           this.productForm={
        unitIncreaseNumber:1,
        id: 0,
        specification:'',
        specifications: ["鲸致标准"],
        price: 0.0,
        number: 0,
        url: "",
        disType: 0,
        disPercent: 0,
        disAmount: 0,
        memberPrice: 0,
        counterPrice: 0.0,
        salesNumber: 0,
        serviceTimes: 0,
        serviceDuration: 0,
        timeRange: []
      };
      }else{
        this.tempIndex=type;

        let temprow=JSON.parse(JSON.stringify(row))
        temprow.specification=row.specifications[0];
        console.log(row);
        this.productForm =temprow;// Object.assign({}, row);
        // this.productForm.specifications=row.specifications[0];
        this.productFormType='edit';
      }
    },
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url;
      this.$refs["productForm"].validateField("url");
    },
    handleProductEdit() {
      this.$refs["productForm"].validate(valid => {
        if (valid) {
          this.productForm.specifications=[this.productForm.specification];
          this.productForm.updateTime = "";
          if (this.productForm.disType == 0) {
            this.productForm.disPercent = 0;
            this.productForm.disAmount = 0;
          } else if (this.productForm.disType == 1) {
            this.productForm.disAmount = 0;
          } else this.productForm.disPercent = 0;


          this.productForm.specifications[0]=this.productForm.specification;
         if(this.productFormType=='create'){
             this.products.push(this.productForm);
          }else{
          for (var i = 0; i < this.products.length; i++) {
            const v = this.products[i];
            if (
              (v.id === this.productForm.id && this.productForm.id != "") ||
              (this.productForm.id == "" &&
                v.currentId === this.productForm.currentId&&v.currentId!=undefined)
            ) {
              this.products.splice(i, 1, this.productForm);
              break;
            }
          }
          if(this.productForm.id==''){
            console.log(this.tempIndex);
            this.products[this.tempIndex]=this.productForm;
          }
          }
          this.productVisiable = false;
        }
      });
    },
    handleAttributeShow(row) {
      if (row.id) {
        this.attributeForm = Object.assign({}, row);
        this.attributeAdd = false;
      } else {
        this.attributeForm = {};
        this.attributeAdd = true;
      }
      this.attributeVisiable = true;
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm);
      this.attributeVisiable = false;
    },
    handleAttributeEdit() {
      // 这是一个trick，设置updateTime的值为空，告诉后端这个记录已编辑需要更新。
      this.attributeForm.updateTime = "";
      for (var i = 0; i < this.attributes.length; i++) {
        const v = this.attributes[i];
        if (v.id === this.attributeForm.id) {
          this.attributes.splice(i, 1, this.attributeForm);
          break;
        }
      }
      this.attributeVisiable = false;
    },
    handleAttributeDelete(row) {
      row.deleted = true;
    }
  }
};
</script>

<style>
.el-card {
  margin-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.input-new-keyword {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

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

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

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

.op-container {
  display: flex;
  justify-content: center;
}

.el-radio {
  margin-right: 20px;
}

.adv-img .el-upload--picture-card {
  width: 180px;
  height: 118px;
}

.adv-img .el-upload-list--picture-card .el-upload-list__item {
  width: 180px;
  height: 118px;
}

.tag-input {
  width: 240px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  padding: 0 15px;
  overflow: hidden;
  height: 32px;
  background-color: #fff;
}
</style>
