<script src="../../utils/validate.js"></script>

<template>
  <div class="app-container">
    <!-- 右侧导航 -->
    <div class="tree-nav">
      <div class="tree-nav-item" @click="scrollingTo(0)">
        <div :class="['dot', treeNavIndex == 0 ? 'active-tree' : '']">1</div>
        <div>商品基本信息</div>
      </div>
      <div class="tree-nav-item" @click="scrollingTo(1)">
        <div :class="['dot', treeNavIndex == 1 ? 'active-tree' : '']">2</div>
        <div>规格设置</div>
      </div>
      <div class="tree-nav-item" @click="scrollingTo(2)">
        <div :class="['dot', treeNavIndex == 2 ? 'active-tree' : '']">3</div>
        <div>商品售卖渠道</div>
      </div>
      <div class="tree-nav-item" @click="scrollingTo(3)">
        <div :class="['dot', treeNavIndex == 3 ? 'active-tree' : '']">4</div>
        <div>商品特殊设置</div>
      </div>
      <div class="tree-nav-item" @click="scrollingTo(4)">
        <div :class="['dot', treeNavIndex == 4 ? 'active-tree' : '']">5</div>
        <div>商品图片</div>
      </div>
    </div>

    <el-form ref="goods" :rules="rules" :model="goods" label-width="120px" labelPosition="right">
      <el-card class="box-card">
        <h3 ref="navTree1">基本信息</h3>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goods.name" placeholder="商城售卖展示名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编号" prop="goodsSn">
              <el-input v-model="goods.goodsSn" placeholder="请输入商品在公司的内部编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <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-col :span="12">
            <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="12">
            <el-form-item label="商品简称" prop="reportCategory">
              <el-input
                v-model="goods.reportCategory"
                placeholder="多规格商品以商品规格中设置为准"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="商品实际售价" prop="retailPrice">
              <el-input v-model="goods.retailPrice" type="number" placeholder="客户实际需要支付的金额">
                <template slot="append">元</template>
              </el-input>
              <div style="color:red;font-size: 12px">*请填写商品正常售价，而非新客价等特定用户价格</div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            <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-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-row>
          <el-col :span="12">
            <el-form-item label="是否热卖" prop="isHot">
              <el-switch v-model="goods.isHot" active-text="热卖" inactive-text="普通"></el-switch>
              <!-- <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="12">
            <el-form-item label="上下架" prop="isOnSale">
              <el-switch v-model="goods.isOnSale" active-text="上架" disabled inactive-text="下架"></el-switch>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否新客专享" prop="isNew">
              <el-switch v-model="goods.isNew" active-text="新客专享" inactive-text="非新客专享"></el-switch>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否隐藏" prop="isHide">
              <el-switch v-model="goods.isHide" active-text="不可见" inactive-text="可见"></el-switch>
              <!-- <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="12">
            <el-form-item label="加盟商复购可见"  >
              <el-switch v-model="goods.fraVisible" active-text="可见" inactive-text="不可见"></el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="推荐商品" prop="recGoods">
              <el-cascader v-model="goods.recGoods" :options="goodsList" expand-trigger="hover"
                placeholder="推荐商品会显示在商详页的下方"
                :props="{ expandTrigger: 'hover', value: 'value', label: 'label', multiple: true }" style="width:100%"
                clearable @change="handleTypeChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sortOrder">
              <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="计提金额" 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="库存预估数量">
              <el-input
                v-model="productForm.number"
                placeholder="主要用户抖音侧提审，0表示无库存限制"
                type="number"
              />
            </el-form-item>
          </el-col>

        </el-row>-->
      </el-card>

      <el-card class="box-card">
        <h3 ref="navTree2">规格类型设置</h3>
        <el-row>
          <el-form-item label="规格类型" prop="sku">
            <el-radio-group v-model="goods.productType" @input="productTypeChange">
              <el-radio :label="1">单规格</el-radio>
              <el-radio :label="2">多规格</el-radio>
              <!-- <el-radio :label="3" v-if="goods.type != 4">加购</el-radio> -->
              <!-- <el-radio :label="4">无限购</el-radio> -->
            </el-radio-group>
          </el-form-item>
        </el-row>
        <div style="margin:0 0 20px 64px;">
          <el-button :plain="true" type="primary" @click="handleProductShow({}, 0)" size="mini"
            v-if="products.length === 0 || this.goods.productType == 2">添加商品规格
          </el-button>
          <!-- <el-button
            :plain="true"
            type="primary"
            @click="handleProductShow({}, 0)"
            size="mini"
            v-if="goods.productType == 3 && goods.type != 4"
          >加购设置</el-button>-->
        </div>

        <!-- <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-form-item label="商品实际售价" prop="retailPrice">
          <el-input v-model="goods.retailPrice" type="number" placeholder="客户实际需要支付的金额">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="售卖数量">
          <el-input v-model="goods.sales" placeholder="售卖数量" type="number" />
        </el-form-item>-->

        <!-- v-if="goods.productType==3&&goods.type!=4" -->
        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="加购名称">
              <el-input
                v-model="goods.unitDescribe"
                :disabled="goods.type == 4"
                placeholder="如（新居开荒无限加购）"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加购单位">
              <el-input
                v-model="goods.unitArea"
                :disabled="goods.type == 4"
                placeholder="如（平米、台等）"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <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="12">
            <el-form-item label="最多加购数量">
              <el-input v-model="goods.unitMaximum" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>-->

        <!-- v-if="goods.productType != 1" -->
        <el-table :data="products" border>
          <!-- v-if="goods.productType!=3" -->
          <el-table-column property="value" label="基本信息" :key="Math.random()">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">规格名称:</span>
                {{ scope.row.specifications }}
                <br />
                <!--  <span style="font-weight: 600;">规格简称:</span>
                {{ scope.row.shortName }}
                <br/> -->
                <span style="font-weight: 600;">商品属性:</span>
                {{ scope.row.attribute | attributeFilter }}
                <br />
                <span style="font-weight: 600;">商品类型:</span>
                {{ scope.row.type | typeFilter }}
                <br />
                <span style="font-weight: 600;">市场售价:</span>
                {{ scope.row.counterPrice }}
                <br />
                <span style="font-weight: 600;">实际售卖价:</span>
                {{ scope.row.price }}
                <br />
                <span style="font-weight: 600;">新客价:</span>
                {{ scope.row.newCusPrice }}
                <br />
                <span style="font-weight: 600;">限购数:</span>
                {{ scope.row.limit }}
                <br />
                <span style="font-weight: 600;">商品库存:</span>
                {{ scope.row.number }}
                <br />
                <span style="font-weight: 600;">已售数量:</span>
                {{ scope.row.salesNumber }}
                <br />

              </div>
            </template>
          </el-table-column>

          <!-- <el-table-column property="unitIncreaseNumber" label="加购数量" v-if="goods.productType == 3" :key="Math.random()" /> -->
          <el-table-column property="price" label="服务设置" width="150">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">是否支持加购:</span>
                {{ scope.row.isSupportAddbuy == 1 ? '是' : '否' }}
                <br />
                <span style="font-weight: 600;">是否同步给抖音:</span>
                {{ scope.row.isSyncDy == 1 ? '是' : '否' }}
                <br />
                <span style="font-weight: 600;">是否新客价:</span>
                {{ scope.row.isNew == true ? '是' : '否' }}
                <br />
                <span style="font-weight: 600;">最大加购数量:</span>
                {{ scope.row.unitMaximum }}
                <br />
                <span style="font-weight: 600;">加购单位:</span>
                {{ scope.row.unitArea }}
                <br />
                <span style="font-weight: 600;">加购内容:</span>
                {{ scope.row.unitDescribe }}
                <br />
                <span style="font-weight: 600;">加购单价:</span>
                {{ scope.row.unitPrice }}
                <br />
                <span style="font-weight: 600;">计提金额:</span>
                {{ scope.row.serviceFee }}
                <br />
                <span style="font-weight: 600;">服务时长:</span>
                {{ scope.row.serviceDuration }}
                <br />
                <span style="font-weight: 600;">服务次数:</span>
                {{ scope.row.serviceTimes }}
                <br />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="预约设置" width="170">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <span style="font-weight: 600;">所需技能:</span>
                {{ getSkillText(scope.row.serviceSkill) }}
                <br />
                <span style="font-weight: 600;">预约时段类型:</span>
                {{ scope.row.timeRangeType == 1 ? '指定时间段可约' : '固定时间段可约(默认半小时)' }}
                <br />
                <span style="font-weight: 600;">延迟几小时可约:</span>
                {{ scope.row.bookDelayTime }}
                <br />
                <!-- <span style="font-weight: 600;">商品可服务时间:</span>
                {{ scope.row.startTime + '-' + scope.row.endTime }}
                <br/> -->
                <span style="font-weight: 600;">可约期限多少天:</span>
                {{ scope.row.bookIntervalDay }}
                <br />
                <span style="font-weight: 600;">服务时段:</span>
                <div style="margin:-22px 0 0 65px;">
                  <div v-for="(item, index) in scope.row.timeRange" :key="index">{{ item }}</div>
                </div>
                <br />
                <span style="font-weight: 600;">技能人数:</span>
                <div style="margin:-22px 0 0 65px;">
                  <div v-for="(item, index) in scope.row.productSkillList" :key="index">{{ item.skillName }}({{
        item.workerNumber }}人{{ item.serviceLength }}小时) </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="不可约设置" width="170">
            <template slot-scope="scope">
              <div style="text-align: left;">
                <div v-for="(item, index) in scope.row.noServiceTimeRange" :key="index">
                  <span style="font-weight: 600;margin-left:10px;">开始时间:</span>
                  {{ item.startTime }}
                  <span style="font-weight: 600;margin-left:10px;">结束时间:</span>
                  {{ item.endTime }}
                  <span style="font-weight: 600;margin-left:10px;">不可约标签:</span>
                  {{ item.tagName }}
                  <span style="font-weight: 600;margin-left:10px;">提醒内容:</span>
                  {{ item.comment }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column property="url" width="80" label="货品图片">
            <template slot-scope="scope">
              <img v-if="scope.row.url" :src="scope.row.url" width="40" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleProductDelete(scope.row, scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog :visible.sync="productVisiable" title="添加商品规格" width="1160px" :close-on-click-modal="false">
          <el-form ref="productForm" :rules="productRules" :model="productForm" status-icon label-position="right"
            label-width="120px" style="width: 1000px; margin-left:30px;">
            <!-- <el-form-item label="货品规格" prop="specifications">
              <el-tag>
              {{ productForm.specifications[0] }}
            </el-tag>
            </el-form-item>-->
            <!-- v-if="goods.productType!=3" -->
            <h4>基本信息</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="规格名称" prop="specifications">
                  <el-input v-model.trim="productForm.specifications" placeholder="小程序上展示的商品名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格简称" prop="shortName">
                  <el-input v-model.trim="productForm.shortName" placeholder="用于服务商或服务人员快速识别商品服务要求" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品类型" prop="type">
                  <el-select v-model="productForm.type" style="width:100%" placeholder="请选择商品类型">
                    <el-option label="服务类(买约一体)" :value="0" />
                    <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="12">
                <!-- v-if="goods.type === 0 || goods.type == 3"   @change="servieDurationChange"-->
                <el-form-item label="商品属性" prop="attribute">
                  <el-select v-model="productForm.attribute" style="width:100%" 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-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="市场售价" prop="counterPrice">
                  <el-input v-model="productForm.counterPrice" type="number">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实际售卖价" prop="price">
                  <el-input v-model="productForm.price" type="number">
                    <template slot="append">元</template>
                  </el-input>
                  <div style="color:red;font-size: 12px">*请填写商品正常售价，而非新客价等特定用户价格</div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="新客专享" prop="isNew" style="float:left;width:200px;">
                  <el-switch v-model="productForm.isNew" active-text="是" inactive-text="否"></el-switch>
                  <div style="color:red;font-size: 12px;width:200px;margin-left:-80px;">*若该规格存在新客专享价，请勾选</div>
                </el-form-item>
                <el-form-item v-if="productForm.isNew" label="新客价" prop="newCusPrice" style="float:right;width:300px;">
                  <el-input v-model="productForm.newCusPrice" type="number">
                    <template slot="append">元</template>
                  </el-input>
                  <div style="color:red;font-size: 12px;margin-left:-80px;width:300px;">*新客将以该价格成交，购买后，该商品恢复常规价</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="限购件数" prop="limit">
                  <el-input v-model="productForm.limit" type="number" placeholder="每个用户最大可购买数，0为不限购"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="商品库存" prop="number">
                  <el-input v-model="productForm.number" type="number" placeholder="商品库存数量，0表示无库存限制" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已售数量" prop="salesNumber">
                  <el-input v-model="productForm.salesNumber" type="number" />
                  <div style="color:red;font-size: 12px">设置越大在商品列表处展示越靠前</div>
                </el-form-item>
              </el-col>
            </el-row>
            <h4>服务设置</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="是否支持加购" prop="isSupportAddbuy" v-if="goods.productType == 1">
                  <el-radio-group v-model="productForm.isSupportAddbuy">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否同步给抖音" prop="isSyncDy">
                  <el-radio-group v-model="productForm.isSyncDy">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="最大加购数量" prop="unitMaximum"
                  v-if="goods.productType == 1 && productForm.isSupportAddbuy == 1">
                  <el-input v-model="productForm.unitMaximum" type="number" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="加购单位" prop="unitArea"
                  v-if="goods.productType == 1 && productForm.isSupportAddbuy == 1">
                  <el-input v-model="productForm.unitArea" placeholder="比如开荒设置5㎡为一份,则录入[5平方米]" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="加购内容" prop="unitDescribe"
                  v-if="goods.productType == 1 && productForm.isSupportAddbuy == 1">
                  <el-input v-model="productForm.unitDescribe" placeholder="如（新居开荒无限加购）" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="展示单价" prop="unitPrice"
                  v-if="goods.productType == 1 && productForm.isSupportAddbuy == 1">
                  <el-input v-model="productForm.unitPrice" placeholder="每加购单位对应的价格">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <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-col>
              <el-col :span="12">
                <el-form-item label="服务次数" prop="serviceTimes">
                  <el-input v-model="productForm.serviceTimes" 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="计提金额" required>
                  <el-input v-model="productForm.serviceFee" type="number" placeholder="请输入服务人员最大可计提金额">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务顺序" required>
                  <el-select filterable v-model="productForm.serviceSort" style="width:100%" placeholder="选择服务顺序">
                    <el-option label="同时开始(无序)" :value="1" />
                    <el-option label="按先后顺序(有序)" :value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="服务技能" style="float:left;width:340px">
                  <el-select filterable v-model="skillId" placeholder="服务人员需要具备的技能" clearable>
                    <el-option v-for="item in skills" :key="item.id" :label="item.itemName" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="技能时长" label-width="80px" style="float:right;width:160px;">
                  <el-input v-model="serviceLength" type="number"> </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="人数">
                  <el-input style="width:220px;" v-model="workerNumber" type="number">
                  </el-input>
                  <el-button style="float:right;margin-bottom: 10px;" type="primary" @click="addSkillPerson">添加技能人数
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-table :data="productForm.productSkillList" border>
                <el-table-column property="sort" width="50" label="顺序" :key="Math.random()" />
                <el-table-column property="skillId" width="80" label="技能id" />
                <el-table-column property="skillName" label="技能名称" />
                <el-table-column property="serviceLength" width="100"  label="技能时长" />
                <el-table-column property="workerNumber" width="100" label="服务人数" />
                <el-table-column property="refundProportion" label="退款比例（累计为100）" >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.refundProportion" type="number" min="0" max="100" placeholder="累计为100">
                    <template slot="append">%</template>
                  </el-input>
                  </template>
                </el-table-column>
                <el-table-column property="endTime" label="操作" width="150">
                  <template slot-scope="scope">
                    <el-button type="text" size="mini" icon="el-icon-close"
                      @click="delSkillPerson(scope.row, scope.$index)">删除
                    </el-button>
                    <el-button type="text" size="mini" icon="el-icon-top" @click="moveTop(scope.row, scope.$index)">置顶
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>

            <h4>预约设置</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="预约时段类型" prop="timeRangeType">
                  <el-select v-model="productForm.timeRangeType" style="width:100%" placeholder="可约时间段类型">
                    <el-option label="固定时间段可约(默认半小时)" :value="0" />
                    <el-option label="指定时间段可约" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="延迟几小时可约" prop="bookDelayTime">
                  <el-input v-model="productForm.bookDelayTime" type="number"
                    placeholder="预约时，可以从几小时后开始预约，0或空值表示默认（默认14小时）">
                    <template slot="append">小时</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-row v-if="productForm.timeRangeType==0">
              <el-col :span="12">
                <el-form-item label="开始时段" prop="startWorkTime">
                  <el-time-select
                    v-model="productForm.startTime"
                    :picker-options="{
                                    start: '00:00',
                                    step: '0:30',
                                    end: '24:00'
                                }"
                    placeholder="选择时间"
                  ></el-time-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时段" prop="endTime">
                  <el-time-select
                    v-model="productForm.endTime"
                    :picker-options="{
                                    start: '00:00',
                                    step: '0:30',
                                    end: '24:00'
                                }"
                    placeholder="选择时间"
                  ></el-time-select>
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row>
              <el-col :span="12">
                <el-form-item label="购买后可约最晚多少天的档期" prop="bookIntervalDay">
                  <el-input v-model="productForm.bookIntervalDay" type="number" placeholder="可以预约多少天内的档期">
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
           </el-col>
   </el-row>
              <el-row>-->
              <el-col :span="12">
                <el-form-item label="服务时段" prop="timeRange" v-if="productForm.timeRangeType == 1">
                  <el-select v-model="productForm.timeRange" placeholder="请按顺序选择服务时段" multiple clearable
                    style="width:100%">
                    <el-option v-for="item in timerange_p" :key="item.range" :label="item.range" :value="item.range" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <h4>不可约设置</h4>
            <el-row>
              <el-col :span="12">
                <el-form-item label="不可约时间" prop="noServiceRange">
                  <el-date-picker v-model="noServiceRangeForm.noServiceRange" type="datetimerange" class="filter-item"
                    style="width:100%" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    :picker-options="{}" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="不可约提醒" prop="tagName">
                  <el-select v-model="noServiceRangeForm.tagName" style="width:100%" clearable
                    placeholder="预约时段选择时展示在不可约时段后">
                    <el-option label="已约满" :value="'已约满'" />
                    <el-option label="不可约" :value="'不可约'" />
                    <el-option label="即将开放预约" :value="'即将开放预约'" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="不可约提醒内容" prop="comment">
              <el-input v-model="noServiceRangeForm.comment" type="text" placeholder="此内容会在预约时时间校验不通过时展示" />
            </el-form-item>
            <el-button style="float:right;margin-bottom: 10px;" type="primary" @click="handleNoServiceTimeRange">添加
            </el-button>

            <el-table :data="productForm.noServiceTimeRange" border>
              <el-table-column property="startTime" label="开始时间" :key="Math.random()" />
              <el-table-column property="endTime" label="结束时间" />
              <el-table-column property="tagName" label="不可约标签" />
              <el-table-column property="comment" label="提醒内容" />
              <el-table-column property="endTime" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" size="mini" icon="el-icon-close"
                    @click="handleDeleteNoService(scope.row, scope.$index)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-form-item label="商品sku图片" prop="url">
              <el-upload :action="uploadPath" :show-file-list="false" :headers="headers" :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>

              <span class="info">建议尺寸 300*300</span>
            </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 ref="navTree3">商品售卖渠道</h3>
        <el-form-item label="上线渠道">
          <el-select v-model="goods.channel" style="width: 100%" class="filter-item" placeholder="请选择上线渠道" clearable
            multiple>
            <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-row v-if="goods.channel.includes(26) || goods.channel.includes(107)">
          <el-form-item label="抖音鲸致上线城市" v-if="goods.channel.includes(26)">
            <div style="display: flex;width:100%;flex-direction: column;">
              <div class="tag-input" style="width:100%" @click="selectCityVisibleDY">
                <template>
                  <el-tag v-for="(unit, unique) in selectedSubmitCityDY" :key="unit.id" type="info" closable>{{
        unit.channel == 5 ? 'wx' : 'dy' }} {{ unit.city }}
                  </el-tag>
                </template>
              </div>
              <div style="color:#09afff;">抖音鲸致{{ this.selectedSubmitCityDY.filter(item => (item.channel == 26)).length
                }}个城市
              </div>
            </div>
          </el-form-item>

          <el-form-item label="抖音云嘉上线城市" v-if="goods.channel.includes(107)">
            <div style="display: flex;width:100%;flex-direction: column;">
              <div class="tag-input" style="width:100%" @click="selectCityVisibleYJ">
                <template>
                  <el-tag v-for="(unit, unique) in selectedSubmitCityYJ" :key="unit.id" type="info" closable>{{
        unit.channel == 5 ? 'wx' : 'dy' }} {{ unit.city }}
                  </el-tag>
                </template>
              </div>
              <div style="color:#09afff;">抖音云嘉{{ this.selectedSubmitCityYJ.filter(item => (item.channel == 107)).length
                }}个城市
              </div>
            </div>
          </el-form-item>



          <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-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>
            <div style="color:red">仅商品上线抖音渠道时有效</div>
          </el-form-item>
        </el-row>

        <el-row v-show="goods.channel.includes(110)">
          <el-form-item label="支付宝上线城市">
            <div style="display: flex;width:100%;flex-direction: column;">
              <div class="tag-input" style="width:100%" @click="selectCityVisibleZFB">
                <template>
                  <el-tag v-for="(unit, unique) in selectedSubmitCityZFB" :key="unit.id" type="info" closable>
                    {{
        unit.channel
          == 5 ? 'wx' : 'dy'
      }} {{ unit.city }}
                  </el-tag>
                </template>
              </div>
              <div style="color:#09afff;">
                <!-- 抖音{{ this.selectedSubmitCity.filter(item => item.channel == 26).length }}个城市 -->
                支付宝{{ this.selectedSubmitCityZFB.filter(item => item.channel == 110).length }}个城市
              </div>
            </div>
          </el-form-item>
        </el-row>

        <el-row v-show="goods.channel.includes(112)">
          <el-form-item label="花王上线城市">
            <div style="display: flex;width:100%;flex-direction: column;">
              <div class="tag-input" style="width:100%" @click="selectCityVisibleHW">
                <template>
                  <el-tag v-for="(unit, unique) in selectedSubmitCityHW" :key="unit.id" type="info" closable>
                    {{
        unit.channel
          == 112 ? '' : ''
      }} {{ unit.city }}
                  </el-tag>
                </template>
              </div>
              <div style="color:#09afff;">
                花王{{ this.selectedSubmitCityHW.filter(item => item.channel == 112).length }}个城市
              </div>
            </div>
          </el-form-item>
        </el-row>

        <el-row v-if="goods.channel.includes(5)">
          <el-form-item label="微信上线城市">
            <div style="display: flex;width:100%;flex-direction: column;">
              <div class="tag-input" style="width:100%" @click="selectCityVisibleWX">
                <template>
                  <el-tag v-for="(unit, unique) in selectedSubmitCityWX" :key="unit.id" type="info" closable>
                    {{
        unit.channel
          == 5 ? 'wx' : 'dy'
      }} {{ unit.city }}
                  </el-tag>
                </template>
              </div>
              <div style="color:#09afff;">微信{{ this.selectedSubmitCityWX.filter(item => item.channel == 5).length }}个城市
              </div>
            </div>
          </el-form-item>

          <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-row>
        <el-row>
          <el-col :span="24">
            <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-row>
          <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-row>

        <el-form-item label="分享文案" prop="shareAds">
          <el-input v-model="goods.shareAds" rows="3" type="textarea" placeholder="分享文案"></el-input>
        </el-form-item>-->

        <!-- <el-form-item label="商品复制口令链接">
          <el-input v-model="goods.copyLink" placeholder="商品复制口令链接" />
        </el-form-item>-->
      </el-card>
      <el-card class="box-card">
        <h3 ref="navTree4">服务补差属性设置</h3>
        <el-row>
          <el-col :span="12">
            <el-form-item label="补差类型" prop="itemName">
              <el-select v-model="diffDictListFrom.itemName" style="width:100%" clearable placeholder="请选择补差项">
                <el-option v-for="item in diffDictList" :key="item.id" :label="item.itemName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补差金额" prop="amount">
              <el-input v-model="diffDictListFrom.amount" type="number" placeholder="请输入补差金额">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button style="float:right;margin-bottom: 10px;" type="primary" @click="handleDiffDictList">添加
        </el-button>

        <el-table :data="diffDictListAdd" border>
          <el-table-column property="id" label="补差类型Id" />
          <el-table-column property="itemName" label="补差类型" />
          <el-table-column property="amount" label="默认最低价" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-close"
                @click="handleDeleteDiffDictList(scope.row, scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--        <el-row>
          <el-col :span="12">
            <el-form-item label="每小时加时费" prop="difAddTime">
              <el-input v-model="goods.difAddTime" type="number" placeholder="每小时加时费">

                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="带吸尘器费" prop="difVacuumClean">
              <el-input v-model="goods.difVacuumClean" 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="改约费" prop="difModifyTime">
              <el-input v-model="goods.difModifyTime" type="number" placeholder="改约费">

                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="晚间上门费" prop="difEveningService">
              <el-input v-model="goods.difEveningService" type="number" placeholder="晚间上门费">

                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>-->
      </el-card>

      <el-card class="box-card">
        <h3 ref="navTree5">商品图片</h3>
        <el-row>
          <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-row>

        <div class="adv-img">
          <el-form-item label="宣传画廊" prop="gallery">
            <el-upload :action="uploadPath" :limit="5" :headers="headers" :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 v-if="goods.channel.includes(112)" class="info">(花王渠道)第一张图建议尺寸：325*163</span>
            <span v-else class="info">建议尺寸 750*492 ，第一张图片为首页商品展示图</span>
          </el-form-item>
        </div>

        <!-- <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-form-item label="商品简介">
          <el-input v-model="goods.brief" placeholder="商品介绍子标题" />
        </el-form-item>

        <el-form-item label="服务标准">
          <el-input v-model="goods.serviceStandards" placeholder="服务标准" />
        </el-form-item>

        <el-form-item label="服务须知">
          <el-input v-model="goods.serviceInstructions" placeholder="服务标准" />
        </el-form-item>
        <el-form-item label="预约提示数据" prop="goodsTipId">
          <el-select v-model="goods.goodsTipId" style="width:100%" placeholder="选择预约提示数据" clearable>
            <!-- <el-option v-for="item in goodsTips" :key="item.id" :label="'【'+item.type+'】'+item.remark.join(',')" :value="item.id" /> -->
            <el-option v-for="item in goodsTips" :key="item.id" :label="item.type" :value="item.id" />
          </el-select>
        </el-form-item>

        <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="handlePublish">添加</el-button>
      <el-button type="info" v-if="goods.channel.includes(26) || goods.channel.includes(107)"
        @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="selectedCurrentCity" :tabs="selectCityTabs" :activeTab="selectCityActiveTab" />
  </div>
</template>

<script>
import {
  dyGoods,
  getChannelCitys,
  getDiffDictList,
  getGoodsTip,
  getShop,
  getSkills,
  listCatAndBrand,
  listGoods3,
  publishGoods
} from "@/api/goods";
import {listAllCity} from "@/api/city";
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 {MessageBox} from "element-ui";
import {getToken} from "@/utils/auth";

const typeMap = {
  0: "无奖励",
  1: "实收金额百分比",
  2: "固定奖励金额"
};
let vm
export default {
  name: "GoodsCreate",
  components: {Editor, selectCity},
  beforeCreate() {
    vm = this;
  },
  filters: {
    disTypeFilter(type) {
      return typeMap[type];
    },
    attributeFilter(value) {
    const rs = vm.productAttributes.filter((item) => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }
    },
    typeFilter(value) {
    const rs = vm.productType.filter((item) => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }}
  },

  data() {
    var isDuration = (rule, value, callback) => {
      if (this.goods.type != 0 && this.goods.type != 2) {
        callback();
      } else {
        var number = /^\d+$|^\d+[.]?\d+$/;
        if (!number.test(value) || value <= 0) {
          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 validateGoodsAttribute = (rule, value, callback) => {
      if (
        (this.productForm.type === 0 || this.productForm.type === 3) &&
        this.productForm.attribute == ""
      )
        callback(new Error("商品属性不能为空"));
      else callback();
    };

    var validateTimeRange = (rule, value, callback) => {
      if (
        (this.productForm.type === 0 || this.productForm.type === 3) && this.productForm.timeRangeType == 1 &&
        (this.productForm.timeRange == "" ||
          this.productForm.timeRange.length == 0)
      )
        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 {
      skillId:'',
      workerNumber:0,
      serviceLength:0,

      treeNavIndex: 0,
      meunrefs: ["navTree1", "navTree2", "navTree3", "navTree4", "navTree5"],
      productFormType: "",
      fraList: [],
      channels: [],
      selectCityVisible: false,
      selectCityTabs: [],
      selectCityActiveTab: "",
      selectedSubmitCity: [], //城市选择控件回传的值
      selectedCurrentCity: [],
      selectedSubmitCityDY: [],
      selectedSubmitCityWX: [],
      selectedSubmitCityZFB: [],
      selectedSubmitCityHW:[],
      selectedSubmitCityYJ:[],
      uploadPath,
      timeArray: [],
      newKeywordVisible: false,
      newKeyword: "",
      sCategory: [], //统计分类 报表时使用
      units: [
        {unit: "次"}
        // { unit: "2次" },
        // { unit: "4次" },
        // { unit: "24次" },
        // { unit: "48次" }
      ], //规格
      timerange: [], //可约时间范围
      timerange_s: [], //跟进服务时间 筛选后的时间范围
      activityArray: [], //限时活动时间
      keywords: [],
      categoryList: [],
      brandList: [],
      citys: [], //业务城市
      shops: [],
      skills: [],
      goodsTips: [],
      goods: {
        picUrl: "",
        shareUrl: "",
        shareWxUrl: "",
        gallery: [],
        isHot: false,
        isNew: false,
        isOnSale: false,
        isHide: false,
        sortOrder: 99,
        shops: [],

        channel: [],
        verifyType: "",
        isOnlyLive: false,
        reportCategory: "",
        applicableTemplate: "",
        limit: 0,
        assignFraId: "",
        recGoods: [],
        sales: "",
        serviceStandards: "",
        serviceInstructions: "",
        productType: 1,
        dispatchType: 1,
        difAddTime: "",
        difVacuumClean: "",
        difModifyTime: "",
        difEveningService: "",

        goodsTipId: "",
        fraVisible:"",
      },
      goodsSupplement: [],
      submiting: false, //商品提交中 防止多次提交
      specVisiable: false,
      specForm: {specification: "", value: "", picUrl: ""}, //规格表
      multipleSpec: false,
      specifications: [],
      // specifications: [
      //   { specification: "规格", value: "鲸致标准", picUrl: "" },
      // ],
      productVisiable: false,
      productForm: {
        unitIncreaseNumber: 1,
        shortName: "",
        id: 0,
        specifications: "",
        attribute: 1,
        type: 0,
        price: 0.0,
        number: 0,
        url: "",
        disType: 0,
        disPercent: 0,
        disAmount: 0,
        memberPrice: 0,
        counterPrice: 0.0,
        salesNumber: 0,
        serviceTimes: 0,
        serviceDuration: 0,
        timeRange: [],
        isSupportAddbuy: 0,
        isSyncDy: 0,
        unitDescribe: "",
        unitArea: "",
        unitPrice: "",
        unitMaximum: 0,
        serviceSkill: "",
        serviceFee: "",
        serviceSort: 1,
        timeRangeType: 0,
        bookDelayTime: 0,
        startTime: "",
        endTime: "",
        bookIntervalDay: "",
        noServiceTimeRange: [],
        productSkillList:[]
      },
      timerange_p: [], //sku跟进服务时间 筛选后的时间范围
      products: [],
      // products: [
      //   {
      //     id: 0,
      //     specifications: ["鲸致标准"],
      //     price: 0.0,
      //     number: 0,
      //     url: "",
      //     disType: 0,
      //     disPercent: 0,
      //     disAmount: 0,
      //   },
      // ],
      dyFormVisiable: false,
      dyForm: {
        goodsId: "",
        goodsName: "",
        version: "",
        remark: ""
      },
      attributeVisiable: false,
      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"
          }
        ],
        value: [{required: true, message: "规格值不能为空", trigger: "blur"}],
        specification: [
          {required: true, message: "规格不能为空", trigger: "blur"}
        ],
        applicableTemplate: [
          {required: true, message: "请选择核销方式", trigger: "change"}
        ],
        categoryId: [
          {
            type: "number",
            required: true,
            message: "请选择商品分类",
            trigger: "change"
          }
        ],
        picUrl: [
          {required: true, message: "商品图片不能为空", trigger: "blur"}
        ],
        gallery: [
          {
            type: "array",
            required: true,
            message: "宣传栏至少需要一个",
            trigger: "blur"
          }
        ],
        serviceDuration: [
          {validator: isDuration, required: true, trigger: "change"}
        ],
        shops: [{type: "array", required: true, message: "所属门店不能为空"}],
        serviceSkill: [
          {
            type: "array",
            validator: isNeedSkill,
            required: true,
            trigger: "change"
          }
        ],
        serviceTimes: [
          {validator: isServiceTimes, required: true, trigger: "blur"}
        ],
        price: [
          {required: true, message: "实际售价不能为空", trigger: "blur"}
        ],
        activityPrice: [
          {
            validator: activityPriceValidate,
            required: true,
            message: "活动价不能为空",
            trigger: "blur"
          }
        ],
        retailPrice: [
          {required: true, message: "实际售价不能为空", trigger: "blur"}
        ],
        // memberPrice: [
        //   { required: true, message: "会员价不能为空", rigger: "blur" },
        // ],

        number: [{required: true, message: "库存不能为空", trigger: "blur"}],
        // reportCategory: [
        //   {required: true, message: "商品简称不能为空", trigger: "blur"}
        // ],
        // goodsSupplement:[
        //   {required: true, message: "关联商品不能为空", trigger: "blur"}
        // ]
        dispatchType: [
          {required: true, message: "请选择派单方式", trigger: "blur"}
        ],
        timeRange: [
          {
            required: true,
            message: "请选择服务时段",
            trigger: "blur"
          }
        ]
      },
      productRules: {
        specifications: [
          {required: true, message: "规格名称不能为空", trigger: "blur"}
        ],
        shortName: [
          {required: true, message: "规格简称不能为空", trigger: "blur"}
        ],
        unitIncreaseNumber: [
          {required: true, message: "加购数量不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "实际售价不能为空", trigger: "blur"}
        ],
        counterPrice: [
          {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"}
        ],
        attribute: [
          {
            validator: validateGoodsAttribute,
            required: true,
            message: "请选择商品属性",
            trigger: "blur"
          }
        ],
        type: [
          {required: true, message: "请选择商品类型", trigger: "blur"}
        ],
        number: [
          {required: true, message: "库存不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (value > 10000000) {
                callback(new Error("库存不能超过一千万"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }

        ],
        salesNumber: [
          {required: true, message: "销量不能为空", trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (value > 10000000) {
                callback(new Error("销量不能超过一千万"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        serviceTimes: [
          {validator: isServiceTimes, required: true, trigger: "blur"},
          {
            validator: (rule, value, callback) => {
              if (value > 48) {
                callback(new Error("服务次数不能超过48次"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
      },
      editorInit: {
        language: "zh_CN",
        language_url: "https://mall.zhaijieshi.cc/tinymce4.7.5/langs/zh_CN.js",
        height: 500,
        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},
        {name: "预约商品", id: 5}
      ],

      goodsList: [], // 三级商品
      noServiceRangeForm: {
        noServiceRange: [],
        comment: "",
        tagName: ""
      }, //不可约时间 范围
      noServiceRanges: [], //不可约时间范围 列表，
      diffDictList: [], //补差项名称，
      diffDictListFrom: {
        amount: "",
        itemName: ""
      },
      diffDictListAdd: [],
      productAttributes:[{id:1,name:"单次"},{id:2,name:"品类"},{id:3,name:"周期"},{id:4,name:"保姆钟点工"},{id:5,name:"收纳"},{id:6,name:"其他"}],
      productType:[{id:0,name:"服务类(买约一体)"},{id:2,name:"中介"},{id:3,name:"服务类(买约分离)"},{id:5,name:"代金券"},{id:6,name:"实物商品"}]
    };
  },
  computed: {
    headers() {
      return {
        "X-Jz-Admin-Token": getToken()
      };
    }
  },
  created() {
    // this.getChannelCitys();
    this.init();
    this.handleListGoods();
    this.getDiffDictList();
  },
  mounted() {
    window.addEventListener("scroll", this.scrolling);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrolling);
  },
  methods: {
    getSkillText(id){
      for(let i=0;i<this.skills.length;i++){
        if(this.skills[i].id == id){
          return this.skills[i].itemName;
        }
      }
    },
    scrolling() {
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      let meunScrolling = this.getScrollTop();
      for (let i in meunScrolling) {
        if (scrollTop <= meunScrolling[i]) {
          this.treeNavIndex = i;
          return;
        }
      }
      this.treeNavIndex = 4;
    },
    getScrollTop() {
      let tops = [];
      for (let i = 1; i < this.meunrefs.length; i++) {
        let ref = this.meunrefs[i];
        let top =
          this.$refs[ref].getBoundingClientRect().top + window.scrollY - 120;
        tops.push(top);
      }
      return tops;
    },
    scrollingTo(num) {
      let top = 0;
      if (num !== 0) {
        let ref = this.meunrefs[num];
        top =
          this.$refs[ref].getBoundingClientRect().top + window.scrollY - 100;
      }
      window.scrollTo({top: top, behavior: "smooth"});
      setTimeout(() => {
        this.treeNavIndex = num;
      }, 100);
    },
    init() {
      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;
      });
      getGoodsTip().then(res => {
        this.goodsTips = res.data.data;
      });
      getShop().then(res => {
        //console.info(res);
        this.shops = res.data.data;
      });

      // getStatisticsCategory().then(res => {
      //   this.sCategory = res.data.data;
      // });
      this.getTimeRange();

      allChannel().then(res => {
        this.channels = res.data.data.filter(item => {
          return (
            item.id == 5 || item.id == 26 || item.id == 38 || item.id >= 102
          );
        });
      });
      getAllFras().then(res => {
        this.fraList = res.data.data;
      });
    },
    handleNoServiceTimeRange() {
      if (
        this.noServiceRangeForm.noServiceRange.length == 0 ||
        this.noServiceRangeForm.comment == ""
      ) {
        this.$message({
          type: "warning",
          message: "请选择不可约时间和提醒内容!"
        });
        return;
      }
      if (this.noServiceRangeForm.tagName == "") {
        this.$message({
          type: "warning",
          message: "请选择不可约标签显示内容!"
        });
        return;
      }

      let startTime = this.noServiceRangeForm.noServiceRange[0];
      let endTime = this.noServiceRangeForm.noServiceRange[1];
      //是否存在重复时间段
      let isCover = false;
      if (this.noServiceRanges.length > 0) {
        this.noServiceRanges.forEach(time => {
          if (
            (time.startTime <= startTime && time.endTime >= startTime) ||
            (time.startTime <= endTime && time.endTime >= endTime)
          ) {
            isCover = true;
          }
        });
      }

      if (isCover) {
        this.$message({
          type: "warning",
          message: "不可约时间存在重叠 请修改!"
        });
        return;
      }

      let noService = {
        startTime: startTime,
        endTime: endTime,
        comment: this.noServiceRangeForm.comment,
        tagName: this.noServiceRangeForm.tagName
      };
      this.noServiceRanges.push(noService);
      this.productForm.noServiceTimeRange = this.noServiceRanges;
      this.noServiceRangeForm = {
        noServiceRange: [],
        comment: ""
      };
    },
    handleDeleteNoService(row, index) {
      this.noServiceRanges.splice(index, 1);
      this.productForm.noServiceTimeRange = this.noServiceRanges;
    },
    async getShop(value) {
      console.info({channelId: value});
      return await getShop({channelId: value});
    },
    isNumber(rule, value, callback) {
      if (value === "") {
        return callback();
      } //这是用来判断如果不是必须输入的，则直接跳出
      const r = /^\+?[1-9][0-9]*$/; // 正整数
      // 如果判断不符合正则，则不是正整数不能提交
      if (!r.test(value)) {
        return callback(new Error("数量必须为正整数"));
      } else {
        return callback();
      }
    },
    getTimeRange() {
      allRange().then(res => {
        this.timerange = res.data.data;
        console.log("shijianduan",res.data.data);
      });
    },
    isInputValid(rule, value, callback) {
      if (value == null || value.trim() == "")
        return callback(new Error("请输入参数或值"));
      else return callback();
    },
    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"});
    },
    goodsValidate() {
      if (this.timeArray && this.timeArray.length === 2) {
        this.goods.bookStartDate = this.timeArray[0];
        this.goods.bookEndDate = this.timeArray[1];
      }
      // this.selectedSubmitCity = this.selectedSubmitCityDY
      //   .concat(this.selectedSubmitCityWX)
      this.selectedSubmitCity =[];
      if(this.goods.channel.includes(5)){
        this.selectedSubmitCity = this.selectedSubmitCity.concat(this.selectedSubmitCityWX);
      }
      if(this.goods.channel.includes(26)){
        this.selectedSubmitCity = this.selectedSubmitCity.concat(this.selectedSubmitCityDY);
      }
      if(this.goods.channel.includes(110)){
        this.selectedSubmitCity = this.selectedSubmitCity.concat(this.selectedSubmitCityZFB);
      }
      if(this.goods.channel.includes(112)){
        this.selectedSubmitCity = this.selectedSubmitCity.concat(this.selectedSubmitCityHW);
      }
      if(this.goods.channel.includes(107)){
        this.selectedSubmitCity = this.selectedSubmitCity.concat(this.selectedSubmitCityYJ);
      }

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

      //验证
      var isCanSubmit = true;
      this.$refs["goods"].validate(valid => {
        isCanSubmit = valid;
      });

      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;
      }
      //低价提醒 防止错误设置
      if (this.goods.counterPrice <= 0) {
        this.$message({
          type: "warning",
          message: "市售价格必须大于0!"
        });
        return false;
      }

      if (isCanSubmit == false) return false;

      return true;
    },
    handlePublish: function () {
      if (this.goodsValidate()) this.fn_publish();
    },
    fn_publish() {
      if (this.submiting) return;
      this.submiting = true;

      if (this.activityArray && this.activityArray.length > 1) {
        this.productForm.activityStart = this.activityArray[0];
        this.productForm.activityEnd = this.activityArray[1];
      }
      let goodsParam = JSON.parse(JSON.stringify(this.goods));
      let recGoods = goodsParam.recGoods;
      let list = [];
      recGoods.forEach(item => {
        list.push(item[2]);
      });

      // goodsParam.recGoods = list;
      goodsParam.gallery = this.goods.gallery.join(",");
      goodsParam.channel = this.goods.channel.join(",");
      goodsParam.recGoods = list.join(",");
      let products = [];

      let proList = JSON.parse(JSON.stringify(this.products));
      proList.forEach(pro => {
        var proItem = pro;
        proItem.productType = this.goods.productType;
        proItem.timeRange = pro.timeRange.join(",");
        // if (this.goods.productType == 2) {
        //   proItem.specifications = [pro.specification];
        // }
        products.push(proItem);
      });
      // }

      let finalGoods = {
        goods: goodsParam,
        // specifications: this.specifications,
        products: products,
        // goodsAddPurchase: products,
        attributes: this.attributes,
        selectedCitys: this.selectedSubmitCity,
        goodsSupplement: this.goodsSupplement,
        // noServiceTimeRange: this.noServiceRanges,
        diffDictListAdd: this.diffDictListAdd
      };

      publishGoods(finalGoods)
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "创建成功"
          });
          this.$router.push({path: "/goods/list"});
        })
        .catch(response => {
          MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
            confirmButtonText: "确定",
            type: "error"
          });
        });
      this.submiting = false;
    },
    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.submiting) return;
      this.submiting = true;

      if (this.activityArray && this.activityArray.length > 1) {
        this.productForm.activityStart = this.activityArray[0];
        this.productForm.activityEnd = this.activityArray[1];
      }
      let products = [];
      // if (this.goods.productType == 1 || this.goods.productType == 4) {
      //   products = [
      //     {
      //       specifications: ["鲸致标准"],
      //       number: 999999,
      //       price: this.goods.retailPrice,
      //       counterPrice: this.goods.counterPrice,
      //       url: this.goods.picUrl,
      //       serviceTimes: this.goods.serviceTimes,
      //       serviceDuration: this.goods.serviceDuration,
      //       timeRange: this.goods.timeRange
      //     }
      //   ];
      // } else {
      let proList = JSON.parse(JSON.stringify(this.products));
      proList.forEach(pro => {
        var proItem = pro;
        proItem.productType = this.goods.productType;
        proItem.timeRange = pro.timeRange.join(",");
        // if (this.goods.productType == 2) {
        //   proItem.specifications = [pro.specification];
        // }
        products.push(proItem);
      });
      // }

      let finalGoods = {
        goods: this.goods,

        products: products,
        attributes: this.attributes,
        selectedCitys: this.selectedSubmitCity,
        external: this.dyForm,
        goodsSupplement: this.goodsSupplement
        // noServiceTimeRange: this.noServiceRanges
      };

      finalGoods.goods.channel = finalGoods.goods.channel.join(",");
      finalGoods.goods.gallery = finalGoods.goods.gallery.join(",");
      dyGoods(finalGoods)
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "创建成功"
          });
          this.$router.push({path: "/goods/list"});
        })
        .catch(response => {
          MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
            confirmButtonText: "确定",
            type: "error"
          });
        });
      this.submiting = false;
    },
    getChannelCitys() {
      getChannelCitys().then(res => {
        this.channelCitys = res.data.data;
      });
    },
    selectCityVisibleDY() {
      this.selectCityVisible = true;
      this.selectCityTabs = ["抖音鲸致"];
      this.selectCityActiveTab = "抖音鲸致";
      this.selectedCurrentCity = this.selectedSubmitCityDY;
    },
    selectCityVisibleYJ() {
      this.selectCityVisible = true;
      this.selectCityTabs = ["抖音云嘉"];
      this.selectCityActiveTab = "抖音云嘉";
      this.selectedCurrentCity = this.selectedSubmitCityYJ;
    },
    selectCityVisibleWX() {
      this.selectCityVisible = true;
      this.selectCityTabs = ["微信商城"];
      this.selectCityActiveTab = "微信商城";
      this.selectedCurrentCity = this.selectedSubmitCityWX;
    },
    selectCityVisibleZFB() {
      this.selectCityVisible = true;
      this.selectCityTabs = ["支付宝"];
      this.selectCityActiveTab = "支付宝";
      this.selectedCurrentCity = this.selectedSubmitCityZFB;
    },
    selectCityVisibleHW(){
      this.selectCityVisible = true;
      this.selectCityTabs = ["花王"];
      this.selectCityActiveTab = "花王";
      this.selectedCurrentCity = this.selectedSubmitCityHW;
    },
    submitSelectCity(param) {
      console.info(param);
      if (this.selectCityActiveTab == "抖音鲸致") {
        this.selectedSubmitCityDY = param.citySelected;
      } else if (this.selectCityActiveTab == "微信商城") {
        this.selectedSubmitCityWX = param.citySelected;
      } else if (this.selectCityActiveTab == "支付宝") {
        this.selectedSubmitCityZFB = param.citySelected;
      } else if (this.selectCityActiveTab == "花王") {
        this.selectedSubmitCityHW = param.citySelected;
      } else if (this.selectCityActiveTab == "抖音云嘉") {
        this.selectedSubmitCityYJ = param.citySelected;
      }

      this.selectCityVisible = false;
    },
    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;
      this.$refs["goods"].validateField("picUrl");
    },
    uploadSharePicUrl: function (response) {
      this.goods.shareUrl = response.data.url;
      this.$refs["goods"].validateField("shareUrl");
    },
    uploadShareWxPicUrl: function (response) {
      this.goods.shareWxUrl = response.data.url;
      this.$refs["goods"].validateField("shareWxUrl");
    },
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!"
      });
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url);
      }
      this.$refs["goods"].validateField("gallery");
    },
    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);
        }
      }
    },

    uploadSpecPicUrl: function (response) {
      this.specForm.picUrl = response.data.url;
    },
    handleSpecificationShow() {
      //规格表
      this.specForm = {specification: "", value: "", picUrl: ""};
      this.specVisiable = true;
    },
    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;

      // this.specToProduct(this.specForm);
      let obj = Object.assign(
        {
          id: "",
          specifications: [this.specForm.specification],
          price: 0.0,
          number: 0,
          url: "",
          disType: 0,
          disPercent: 0,
          disAmount: 0,
          memberPrice: 0,
          counterPrice: 0.0,
          salesNumber: 0,
          serviceTimes: 0,
          serviceDuration: 0,
          timeRange: [],
          currentId: index
        },
        this.specForm
      );
      this.products.push(obj);
    },
    handleSpecificationDelete(row) {
      const index = this.specifications.indexOf(row);
      this.specifications.splice(index, 1);
      this.products.splice(index, 1);
      // this.specToProduct(row);
    },
    servieDurationChange(value) {
      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);
      this.productForm.timeRange = [];
      this.timerange_p = [];
      this.timerange.forEach(time => {
        if (
          time.duration == this.productForm.serviceDuration &&
          time.type == this.productForm.attribute
        )
          this.timerange_p.push({range: time.startTime + "-" + time.endTime});
      });
    },
    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;
      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);
    },
    handleProductDelete(row,index) {
      this.products.splice(index, 1);
    },
    handleProductShow(row, type) {
      this.productVisiable = true;

      if (type == 0) {
        this.productFormType = "create";
        this.noServiceRanges = [];
        this.productForm = {
          unitIncreaseNumber: 1,
          shortName: "",
          id: this.products.length,
          specification: "",
          attribute: 1,
          type: 0,
          price: 0.0,
          number: 0,
          url: "",
          counterPrice: 0.0,
          salesNumber: 0,
          serviceTimes: 0,
          serviceDuration: 0,
          timeRange: [],
          isSupportAddbuy: 0,
          isSyncDy: 0,
          unitDescribe: "",
          unitArea: "",
          unitPrice: "",
          unitMaximum: 0,
          serviceSkill: "",
          serviceFee: "",
          serviceSort:1,
          timeRangeType: 0,
          bookDelayTime: 0,
          startTime: "",
          endTime: "",
          bookIntervalDay: "",
          noServiceTimeRange: [],
          productSkillList:[],
          isNew:false,
          newCusPrice:0,
          limit:0,
        };
      } else {
        this.productForm = Object.assign({}, row);
        this.servieDurationChangeP();
        this.$set(this.productForm, 'timeRange', row.timeRange);
        this.productForm.index = row.id;
        this.productFormType = "edit";
        this.noServiceRanges = row.noServiceTimeRange;
      }
    },
    uploadProductUrl: function (response) {
      this.productForm.url = response.data.url;
      this.$refs["productForm"].validateField("url");
    },
    handleProductEdit() {
      console.log(this.productForm);
      this.productForm.noServiceTimeRange = this.noServiceRanges;
      this.$refs["productForm"].validate(valid => {
        if (valid) {
          console.log(this.productForm);

          // this.productForm.specifications = [this.productForm.specification];
          //判断售价
          if (
            !this.productForm.counterPrice ||
            !this.productForm.price ||
            this.productForm.counterPrice == 0 ||
            this.productForm.price == 0 ||
            this.productForm.counterPrice * 1 < this.productForm.price * 1
          ) {
            this.$message({
              type: "warning",
              message: "售价不能为空或市场售价小于销售价格"
            });
            return;
          }

          if((this.productForm.type==0||this.productForm.type==3)){
              if(this.productForm.productSkillList.length==0){
                this.$message({
                      type: "warning",
                      message: "服务类商品需配置技能人数"
                    });
                return;
              }
              let servt=this.productForm.serviceDuration*1;
              let servtck=true;
              let alltm=0;
              this.productForm.productSkillList.forEach(f=>{
                alltm=alltm+f.serviceLength*1;
                if(f.serviceLength*1>servt){
                  servtck=false;
                }
              })
              if(!servtck){
                this.$message({
                      type: "warning",
                      message: "单个技能时长不可超过总服务时长"
                    });
                return;
              }
              if(alltm!=servt&&this.productForm.serviceSort==2){
                this.$message({
                      type: "warning",
                      message: "服务顺序为有序，累计技能时长应等于总服务时长，当前总服务时长为:"+servt+' 累计技能时长为：'+alltm
                    });
                return;
              }
              let sumrefund=0;
              for(let s=0;s<this.productForm.productSkillList.length;s++){
                let rr=this.productForm.productSkillList[s];
                  if(rr.refundProportion==null||rr.refundProportion==0){
                    this.$message({
                    type: "warning",
                    message: "退款比例不可为空"
                  });
                  return;
                }
                sumrefund=sumrefund+rr.refundProportion*1;
              }
              if(sumrefund!=100){
                this.$message({
                  type: "warning",
                  message: "退款累计比例必须为100"
                });
                return;
              }

              if(this.productForm.serviceSort==1){
                //同时开始
                this.productForm.productSkillList.forEach((e,index)=>{
                  e.sort=0;
                })
              }else{
                //有序
                this.productForm.productSkillList.forEach((e,index)=>{
                  e.sort=index+1;
                })
              }
          }

          if (this.productFormType == "create") {
            this.products.push(this.productForm);
          } else {
            for (var i = 0; i < this.products.length; i++) {
              let v = this.products[i];
              if (v.id === this.productForm.id) {
                this.products.splice(i, 1, this.productForm);
                break;
              }
            }
          }

          this.productVisiable = false;
        }
      });
    },
    handleAttributeShow() {
      this.attributeForm = {};
      this.attributeVisiable = true;
    },
    handleAttributeAdd() {
      if (
        this.attributeForm.attribute == null ||
        this.attributeForm.value == null
      ) {
        this.$message({
          type: "warning",
          message: "请输入参数信息"
        });
        return;
      }
      this.attributes.unshift(this.attributeForm);
      this.attributeVisiable = false;
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row);
      this.attributes.splice(index, 1);
    },
    getCity() {
      listAllCity().then(res => {
        this.citys = res.data.data;
        this.citys.splice(0, 0, {id: 0, cityName: "全国"});
        console.info(this.citys);
      });
    },
    handleListGoods() {
      listGoods3()
        .then(res => {
          this.goodsList = res.data.data.goodsList;
          // this.categoryList = res.data.data.categoryList;
        })
        .catch(() => {
        });
    },
    handleTypeChange(value) {
      console.log(value);
    },
    productTypeChange(value) {
      if (value == 4) {
        this.dispatchType = 2;
      }
    },
    getDiffDictList() {
      getDiffDictList()
        .then(res => {
          console.log(2);
          this.diffDictList = res.data.data;
        })
        .catch(res => {
        });
    },
    handleDiffDictList: function () {
      if (
        this.diffDictListFrom.itemName.length == 0 ||
        this.diffDictListFrom.itemName == ""
      ) {
        this.$message({
          type: "warning",
          message: "请选择补差类型!"
        });
        return;
      }

      if (this.diffDictListFrom.amount == "") {
        this.$message({
          type: "warning",
          message: "请输入补差金额!"
        });
        return;
      }
      //是否存在重复补差类型
      let isCover = false;
      if (this.diffDictListAdd.length > 0) {
        this.diffDictListAdd.forEach(time => {
          if (time.id == this.diffDictListFrom.itemName) {
            isCover = true;
          }
        });
      }

      if (isCover) {
        this.$message({
          type: "warning",
          message: "补差类型已存在，请修改！"
        });
        return;
      }
      let result = this.diffDictList.find(item => {
        return item.id == this.diffDictListFrom.itemName;
      });
      let diffDict = {
        id: result.id,
        itemName: result.itemName,
        amount: this.diffDictListFrom.amount
      };
      this.diffDictListAdd.push(diffDict);
      this.diffDictListFrom = {
        itemName: "",
        amount: ""
      };
    },
    handleDeleteDiffDictList(row, index) {
      this.diffDictListAdd.splice(index, 1);
    },
    addSkillPerson(){
      if(this.skillId==null||this.skillId==''){
        this.$message({
          type: "warning",
          message: "请选择技能!"
        });
        return ;
      }
      if(this.workerNumber==null||this.workerNumber==''){
        this.$message({
          type: "warning",
          message: "请输入服务人数!"
        });
        return ;
      }
      if(this.serviceLength==null||this.serviceLength==''||this.serviceLength==0){
        this.$message({
          type: "warning",
          message: "请输入技能服务时长"
        });
        return ;
      }

      let that=this;
      let ck=false;
      this.productForm.productSkillList.forEach(e=>{
        if(e.skillId==that.skillId){
          ck=true;
        }
      })
      if(ck){
        this.$message({
          type: "warning",
          message: "技能已存在，请勿重复添加"
        });
        return ;
      }

      let skname=this;
       this.skills.forEach(e=>{
        if(e.id==that.skillId){
          skname=e.itemName;
        }
       })
        //退款百分比例
      let proportion=(this.productForm.productSkillList.length==0?100:0);


      let skillperson={
        sort: this.productForm.productSkillList.length+1,
        skillId:this.skillId,
        skillName:skname,
        workerNumber:this.workerNumber,
        serviceLength:this.serviceLength,
        refundProportion:proportion
      };
       this.productForm.productSkillList=this.productForm.productSkillList.concat([skillperson]);
       this.productForm.productSkillList.forEach((e,index)=>{
        e.sort=index+1;
      })
    },
    delSkillPerson(row, index){
      this.productForm.productSkillList.splice(index, 1);
      this.productForm.productSkillList.forEach((e,index)=>{
        e.sort=index+1;
      })
    },
    moveTop(row, index) {
      this.productForm.productSkillList.splice(index, 1);
      this.productForm.productSkillList=[row].concat(this.productForm.productSkillList);
    //  let newsList =this.productForm.productSkillList;
    //  newsList.unshift(...newsList.splice(newsList.findIndex(i => i===index), 1))
    this.productForm.productSkillList.forEach((e, index) => {
        e.sort = index + 1;
      })
    }
  }
};
</script>

<style scoped>
.app-container {
  width: 1100px;
  margin: 0 0 0 40px;
  position: relative;
  padding-right: 200px;
}

.app-container h3 {
  text-align: left;
  padding-left: 20px;
}

.app-container h4 {
  font-size: 17px;
}

.el-card.is-always-shadow {
  box-shadow: none;
  border-radius: 0;
  border: 1px solid #666;
  padding-right: 10px;
}

.info {
  font-size: 9px;
  color: #20a0ff;
  margin-left: 15px;
}

.el-card {
  margin-bottom: 20px;
}

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

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

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

.avatar-uploader .el-upload {
  width: 145px;
  height: 145px;
  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;
}

.el-form-item__content {
  display: flex;
}

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

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

.el-radio-group {
  /* margin-top: 10px; */
}

.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;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.tag-input:hover {
  cursor: pointer;
}

.app-container .tree-nav {
  position: fixed;
  top: 140px;
  right: 20px;
  border-left: 2px solid #ddd;
  padding: 10px;
  z-index: 9999;
}

.tree-nav-item {
  display: flex;
  height: 40px;
  align-items: center;
  cursor: pointer;
}

.tree-nav-item .dot {
  width: 24px;
  height: 24px;
  border-radius: 24px;
  line-height: 24px;
  text-align: center;
  color: #fff;
  background: #2a7bf5;
  font-size: 12px;
  margin: 0 10px 0 -22px;
  opacity: 0;
}

.tree-nav-item .dot.active-tree {
  opacity: 1;
}
</style>
