<script src="../../utils/validate.js"></script>
<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>商品介绍</h3>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="goods.goodsSn" />
        </el-form-item>

        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goods.name" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="市场售价" prop="counterPrice">
              <el-input
                v-model="goods.counterPrice"
                type="number"
                placeholder="0.00"
              >
                <template slot="append"
                  >元</template
                >
              </el-input>
            </el-form-item>
          </el-col>
          <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-row>
          <el-col :span="12">
            <el-form-item label="所属门店" prop="shops">
              <el-select
                v-model="goods.shops"
                style="width:100%"
                placeholder="归属哪个门店"
                multiple
                clearable
              >
                <el-option
                  v-for="item in shops"
                  :key="item.id"
                  :label="item.shopName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="limit">
              <el-input
                v-model="goods.sortOrder"
                type="number"
                placeholder="数值越小 排列越靠前"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="商品类型" prop="type">
              <el-radio-group v-model="goods.type">
                <el-radio :label="0">服务类</el-radio>
                <el-radio :label="1">保险类</el-radio>
                <el-radio :label="2">中介类</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否热卖" prop="isHot">
              <el-radio-group v-model="goods.isHot">
                <el-radio :label="false">普通</el-radio>
                <el-radio :label="true">热卖</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上下架" prop="isOnSale">
              <el-radio-group v-model="goods.isOnSale">
                <el-radio :label="true">上架</el-radio>
                <el-radio :label="false">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否新品" prop="isNew">
              <el-radio-group v-model="goods.isNew">
                <el-radio :label="true">新品</el-radio>
                <el-radio :label="false">非新品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="服务时长" prop="serviceDuration">
              <el-input
                v-model="goods.serviceDuration"
                type="number"
                placeholder="完成此服务 需要的时长"
              >
                <template slot="append"
                  >小时</template
                >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务次数" prop="serviceTimes">
              <el-input
                v-model="goods.serviceTimes"
                type="number"
                placeholder="需要的服务次数"
              >
                <template slot="append"
                  >次</template
                >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需技能" prop="serviceSkill">
              <el-select
                v-model="goods.serviceSkill"
                style="width:100%"
                placeholder="完成此项服务，服务人员需要具备的技能"
                clearable
              >
                <el-option
                  v-for="item in skills"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-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-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 class="info">建议尺寸 430*430</span>
        </el-form-item>

        <el-form-item label="商品单位" prop="unit">
          <el-select v-model="goods.unit" clearable>
            <el-option
              v-for="item in units"
              :key="item.unit"
              :label="item.label"
              :value="item.unit"
            />
          </el-select>
        </el-form-item>
        <el-form :rules="rules" :model="productForm" label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品实际售价" prop="price">
                <el-input v-model="productForm.price" type="number">
                  <template slot="append"
                    >元</template
                  >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存预估数量" prop="number">
                <el-input v-model="productForm.number" type="number" />
              </el-form-item>
            </el-col>
          </el-row>

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

              <el-form-item
                v-show="productForm.disType == 2"
                label="固定奖励金额"
                prop="disAmount"
              >
                <el-input v-model="productForm.disAmount" type="number">
                  <template slot="append"
                    >元</template
                  >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

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

          <el-button
            v-else
            class="button-new-keyword"
            type="primary"
            @click="showInput"
            >+ 增加</el-button
          >
        </el-form-item>

        <el-form-item label="所属分类" prop="categoryId">
          <el-cascader
            v-model="goods.categoryId"
            :options="categoryList"
            expand-trigger="hover"
            clearable
            @change="handleCategoryChange"
          />
        </el-form-item>

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

        <el-form-item label="商品详细介绍">
          <editor v-model="goods.detail" :init="editorInit" />
        </el-form-item>

        <!-- <el-form-item label="货品图片" 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">建议尺寸 430*430</span>
          </el-form-item> -->
      </el-form>
    </el-card>

    <!-- <el-card class="box-card">
      <h3>商品规格</h3>
      <el-row :gutter="20" type="flex" align="middle" style="padding:20px 0;">
        <el-col :span="10">
          <el-radio-group v-model="multipleSpec" @change="specChanged">
            <el-radio-button :label="false">默认标准规格</el-radio-button>
            <el-radio-button :label="true">多规格支持</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col v-if="multipleSpec" :span="10">
          <el-button :plain="true" type="primary" @click="handleSpecificationShow">添加</el-button>
        </el-col>
      </el-row>

      <el-table :data="specifications">
        <el-table-column property="specification" label="规格名" />
        <el-table-column property="value" label="规格值">
          <template slot-scope="scope">
            <el-tag type="primary">
              {{ scope.row.value }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="picUrl" label="规格图片">
          <template slot-scope="scope">
            <img v-if="scope.row.picUrl" :src="scope.row.picUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column
          v-if="multipleSpec"
          align="center"
          label="操作"
          width="250"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleSpecificationDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="specVisiable" title="设置规格">
        <el-form
          ref="specForm"
          :rules="rules"
          :model="specForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="规格名" prop="specification">
            <el-input v-model.trim="specForm.specification" />
          </el-form-item>
          <el-form-item label="规格值" prop="value">
            <el-input v-model.trim="specForm.value" />
          </el-form-item>
          <el-form-item label="规格图片" prop="picUrl">
            <el-upload
              :action="uploadPath"
              :show-file-list="false"
              :headers="headers"
              :on-success="uploadSpecPicUrl"
              class="avatar-uploader"
              accept=".jpg,.jpeg,.png,.gif"
            >
              <img v-if="specForm.picUrl" :src="specForm.picUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
            <span class="info">建议尺寸 430*430</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleSpecificationAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card> -->

    <!-- <el-card class="box-card">
      <h3>商品售价、库存、分佣设置</h3>
      <el-table :data="products">
        <el-table-column property="value" label="货品规格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="price" width="100" label="货品售价" />
        <el-table-column property="number" width="100" label="货品数量" />
        <el-table-column v-show="goods.isCr" property="skuId" label="仓库产品编号" />
        <el-table-column property="disType" label="奖励方式">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.disType | disTypeFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="disPercent" label="金额百分比" />
        <el-table-column property="disAmount" label="固定金额" />

        <el-table-column property="url" width="100" 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="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleProductShow(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="productVisiable" title="添加货品">
        <el-form
          ref="productForm"
          :model="productForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 500px; margin-left:50px;"
        >
          <el-form-item label="货品规格列" prop="specifications">
            <el-tag v-for="tag in productForm.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </el-form-item>

          <el-form-item v-show="goods.isCr" label="仓库产品编号" prop="skuId">
            <el-input v-model="productForm.skuId" placeholder="对应仓库的商品id" />
          </el-form-item>

          <el-form-item label="货品售价" prop="price">
            <el-input v-model="productForm.price" type="number">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="货品数量" prop="number">
            <el-input v-model="productForm.number" type="number" />
          </el-form-item>

          <el-form-item label="推广奖励方式" prop="productForm.disType">
            <el-radio-group v-model="productForm.disType">
              <el-radio :label="0">无奖励</el-radio>
              <el-radio :label="1">实收金额百分比</el-radio>
              <el-radio :label="2">固定奖励金额</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-show="productForm.disType==1" label="奖励百分比" prop="disPercent">
            <el-input v-model="productForm.disPercent" type="number" maxlength="2">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>

          <el-form-item v-show="productForm.disType==2" label="固定奖励金额" prop="disAmount">
            <el-input v-model="productForm.disAmount" type="number">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>

          <el-form-item label="货品图片" 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">建议尺寸 430*430</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>商品参数</h3>
      <el-button type="primary" @click="handleAttributeShow">添加</el-button>
      <el-table :data="attributes">
        <el-table-column property="attribute" label="商品参数名称" />
        <el-table-column property="value" label="商品参数值" />
        <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleAttributeDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="attributeVisiable" title="添加商品参数">
        <el-form
          ref="attributeForm"
          :model="attributeForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="商品参数名称" prop="attribute">
            <el-input v-model.trim="attributeForm.attribute" />
          </el-form-item>
          <el-form-item label="商品参数值" prop="value">
            <el-input v-model.trim="attributeForm.value" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="attributeVisiable = false">取消</el-button>
          <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
        </div>
      </el-dialog>
    </el-card> -->

    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">添加</el-button>
    </div>
  </div>
</template>

<script>
import { publishGoods, listCatAndBrand, getSkills, getShop } from "@/api/goods";
import { createStorage, uploadPath } from "@/api/storage";
import Editor from "@tinymce/tinymce-vue";
import { MessageBox } from "element-ui";
import { getToken } from "@/utils/auth";

const typeMap = {
  0: "无奖励",
  1: "实收金额百分比",
  2: "固定奖励金额"
};

export default {
  name: "GoodsCreate",
  components: { Editor },
  filters: {
    disTypeFilter(type) {
      return typeMap[type];
    }
  },

  data() {
    var isDuration = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        var number = /^\d+$|^\d+[.]?\d+$/;
        if (!number.test(value) || value <= 0) {
          callback(new Error("请输入服务时长"));
        } else {
          callback();
        }
      }
    };
    var isNeedSkill = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        if (value == undefined || value == null) {
          callback(new Error("请选择服务所需技能"));
        } else {
          callback();
        }
      }
    };

    var isServiceTimes = (rule, value, callback) => {
      if (this.goods.type != 0) {
        callback();
      } else {
        if (value == undefined || value == null) {
          callback(new Error("请选择所需服务次数"));
        } else {
          callback();
        }
      }
    };
    return {
      uploadPath,
      newKeywordVisible: false,
      newKeyword: "",
      units: [
        { unit: "次" },
        { unit: "2次" },
        { unit: "4次" },
        { unit: "24次" },
        { unit: "48次" }
      ], //规格
      keywords: [],
      categoryList: [],
      brandList: [],
      citys: [], //业务城市
      shops: [],
      skills: [],
      goods: {
        picUrl: "",
        gallery: [],
        isHot: false,
        isNew: true,
        isOnSale: true,
        type: 0,
        sortOrder: 99,
        shops: []
      },
      submiting: false, //商品提交中 防止多次提交
      specVisiable: false,
      specForm: { specification: "", value: "", picUrl: "" }, //规格表
      multipleSpec: false,
      specifications: [
        { specification: "规格", value: "鲸致标准", picUrl: "" }
      ],
      productVisiable: false,
      productForm: {
        id: 0,
        specifications: ["鲸致标准"],
        price: 0.0,
        number: 0,
        url: "",
        disType: 0,
        disPercent: 0,
        disAmount: 0
      },
      products: [
        {
          id: 0,
          specifications: ["鲸致标准"],
          price: 0.0,
          number: 0,
          url: "",
          disType: 0,
          disPercent: 0,
          disAmount: 0
        }
      ],
      attributeVisiable: false,
      attributeForm: { attribute: "", value: "" },
      attributes: [],
      rules: {
        goodsSn: [
          { required: true, message: "商品编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        counterPrice: [
          {
            required: true,
            validator: this.isNumber,
            message: "市场售价不能为空或小于等于0",
            trigger: "blur"
          }
        ],
        // brandId:[{type:'number',required:true,message:"品牌制造商不能为空",rigger: "change"}],
        value: [{ required: true, message: "规格值不能为空", rigger: "blur" }],
        specification: [
          { required: true, message: "规格不能为空", rigger: "blur" }
        ],
        // unit:[{required:true,message:"商品单位不能为空",rigger: "change"}],
        categoryId: [
          {
            type: "number",
            required: true,
            message: "请选择商品分类",
            trigger: "change"
          }
        ],
        picUrl: [
          { required: true, message: "商品图片不能为空", rigger: "blur" }
        ],
        gallery: [
          {
            type: "array",
            required: true,
            message: "宣传栏至少需要一个",
            rigger: "blur"
          }
        ],
        serviceDuration: [
          { validator: isDuration, required: true, rigger: "change" }
        ],
        shops: [{ required: true, message: "所属门店不能为空" }],
        serviceSkill: [
          { validator: isNeedSkill, required: true, rigger: "change" }
        ],
        serviceTimes: [
          { validator: isServiceTimes, required: true, rigger: "blur" }
        ],
        price: [
          { required: true, message: "实际售价不能为空", rigger: "blur" }
        ],
        number: [{ required: true, message: "库存不能为空", rigger: "blur" }]
      },
      editorInit: {
        language: "zh_CN",
        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("上传失败，请重新上传");
            });
        }
      }
    };
  },
  computed: {
    headers() {
      return {
        "X-Jz-Admin-Token": getToken()
      };
    }
  },
  created() {
    this.init();
  },
  methods: {
    init: function() {
      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;
      });
      getShop().then(res => {
        console.info(res);
        this.shops = res.data.data;
      });
    },
    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();
      }
    },
    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];
    },
    handleCancel: function() {
      this.$router.push({ path: "/goods/goods" });
    },
    handlePublish: function() {
      console.info(this.productForm);

      const finalGoods = {
        goods: this.goods,
        specifications: this.specifications,
        products: [this.productForm],
        attributes: this.attributes
      };
      //验证
      var isCanSubmit = true;
      this.$refs["goods"].validate(valid => {
        isCanSubmit = valid;
      });

      if (isCanSubmit == false) return;

      //低价提醒 防止错误设置
      if (this.goods.counterPrice <= 0) {
        this.$message({
          type: "warning",
          message: "市售价格必须大于0!"
        });
        return;
      }
      this.fn_publish(finalGoods);
    },
    fn_publish(finalGoods) {
      if (this.submiting) return;
      this.submiting = true;

      //处理商品归属业务城市
      //if(finalGoods.goods.shops!=null&&typeof finalGoods.goods.shops!='undefined')
      //    finalGoods.goods.shops=finalGoods.goods.shops.join(",");

      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;
    },
    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");
    },
    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);
        }
      }
    },
    specChanged: function(label) {
      if (label === false) {
        this.specifications = [
          { specification: "规格", value: "标准", picUrl: "", disType: 0 }
        ];
        this.products = [
          {
            id: 0,
            specifications: ["标准"],
            price: 0.0,
            number: 0,
            url: "",
            skuId: "",
            disType: 0
          }
        ];
      } else {
        this.specifications = [];
        this.products = [];
      }
    },
    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) {
            this.$message({
              type: "warning",
              message: "已经存在规格值:" + v.value
            });
            this.specForm = {};
            this.specVisiable = false;
            return;
          } else {
            index = i;
          }
        }
      }

      this.specifications.splice(index + 1, 0, this.specForm);
      this.specVisiable = false;

      this.specToProduct();
    },
    handleSpecificationDelete(row) {
      const index = this.specifications.indexOf(row);
      this.specifications.splice(index, 1);
      this.specToProduct();
    },
    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;
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row);
      this.productVisiable = true;
    },
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url;
    },
    handleProductEdit() {
      if (this.productForm.disType == 1 && this.productForm.disPercent <= 0) {
        this.productForm.disAmount = 0;
        this.$message({
          type: "warning",
          message: "实收金额百分比不能为空"
        });
        return;
      }
      if (this.productForm.disType == 2 && this.productForm.disAmount <= 0) {
        this.productForm.disPercent = 0;
        this.$message({
          type: "warning",
          message: "固定奖励金额不能为空"
        });
        return;
      }
      if (this.productForm.disType == 0) {
        this.productForm.disPercent = 0;
        this.productForm.disAmount = 0;
      }

      //this.productForm.disPercent.errmsg="分佣比例不能为空";
      //return;

      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);
    }
  }
};
</script>

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

.el-card {
  margin-bottom: 10px;
}
.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;
}
</style>
