<template>
  <div class="bg-in">
    <div class="content-goods-sku">
      <el-form :model="productForm" :rules="goodsRules" ref="goodsForm">
        <!--商品信息-->
        <div class="base-info-item goods-info">
          <h4>基本信息</h4>
          <div class="goods-info">
            <el-form-item v-if="routerName !== 'goodsAdd'" label="商品编号：">
              <span>{{ productForm.sn }}</span>
            </el-form-item>
            <el-form-item prop="name" label="商品名称：">
              <el-input v-if="isEdit" v-model="productForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入商品名称"></el-input>
              <span v-else>{{ productForm.name }}</span>
            </el-form-item>
            <el-form-item prop="category_id" label="商品类别：">
              <el-cascader v-if="isEdit" v-model="productForm.category_id" :options="categoryList" :props="{
                label: 'name',
                value: 'category_id',
                emitPath: false,
                checkStrictly: true
              }" clearable></el-cascader>
              <span v-else>{{ productForm.category_name }}</span>
            </el-form-item>
            <el-form-item prop="brand_id" label="品牌：">
              <el-select v-if="isEdit" v-model="productForm.brand_id">
                <el-option v-for="item in brandList" :key="item.name" :label="item.name" :value="item.brand_id"></el-option>
              </el-select>
              <span v-else>{{ productForm.brand_name }}</span>
            </el-form-item>
            <template v-if="!productForm.have_spec">
              <el-form-item prop="unit" label="单位：">
                <el-input v-if="isEdit" v-model="productForm.unit" clearable placeholder="请输入商品单位"></el-input>
                <span v-else>{{ productForm.unit }}</span>
              </el-form-item>
              <el-form-item prop="warning_value" label="库存预警数量：">
                <el-input v-if="isEdit" oninput="value = value.replace(/[^\d]/g,'')" v-model="productForm.warning_value" clearable placeholder="请输入库存预警数量"></el-input>
                <span v-else>{{ productForm.warning_value }}</span>
              </el-form-item>
            </template>
          </div>
        </div>
        <!--商品规格-->
        <div class="base-info-item">
          <h4>商品规格</h4>
          <el-form-item prop="have_spec" label="是否为多规格：">
            <el-switch
              v-model="productForm.have_spec"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>

          <div v-show="productForm.have_spec">
            <el-form-item label="" label-width="120px" style="width: 90%;text-align: left;">
              <sku-editor
                ref="skuEditor"
                :goodsInfo="productForm"
                :categoryId="productForm.category_id"/>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="footer">
      <el-button type="primary" size="mini" @click="handleSaveGoods">保存</el-button>
    </div>
  </div>
</template>

<script>
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_Category from '@/api/category'
import * as API_brand from '@/api/basicSetting'
import SkuEditor from '../../components/SkuEditor'

export default {
  name: 'goodsSku',
  components: {
    [SkuEditor.name]: SkuEditor
  },
  data() {
    return {
      goodsId: '',
      // 是否为编辑或添加
      isEdit: false,
      routerName: '',
      // 商品档案数据
      productForm: {
        have_spec: false
      },
      // 分类数据
      categoryList: [],
      goodsRules: {
        name: this.MixinRequired('请输入商品名称！'),
        category_id: { required: true, message: '请选择商品分类！', trigger: 'change'},
        brand_id: { required: true, message: '请选择品牌！', trigger: 'change'},
        unit: this.MixinRequired('请输入商品单位！'),
        warning_value: this.MixinRequired('请输入库存预警数量！')
      },
      // 品牌数据
      brandList: []
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        const name = newVal.name
        const routerList = ['goodsEdit', 'goodsAdd']
        if (routerList.includes(name)) {
          this.routerName = name
          this.isEdit = (name === 'goodsAdd' || name === 'goodsEdit')
          if (name === 'goodsAdd') {
            this.productForm = {
              have_spec: false
            }
          }
          if (newVal.params.id) {
            this.goodsId = newVal.params.id
            this.GET_GoodData()
          }
          this.getCategoryAllChildren()
          this.getBrandAllList()
        }
      }
    }
  },
  methods: {
    /** 获取品牌数据 */
    getBrandAllList() {
      API_brand.getBrandAllList().then(res => {
        this.brandList = res
      })
    },
    /** 获取分类 */
    getCategoryAllChildren() {
      API_Category.getCategoryAllChildren(0).then(response => {
        this.categoryList = response
      })
    },
    /** 商品保存提交 */
    handleSaveGoods() {
      this.$refs['goodsForm'].validate(valid => {
        if (!valid) return
        if (this.productForm.have_spec) {
          this.$refs.skuEditor.submit().then(skus => {
            this.updateProduct(skus)
          })
        } else {
          this.updateProduct()
        }
      })
    },
    /** 新增 & 修改商品 */
    updateProduct(skus = []) {
      const productForm = this.productForm
      if (skus.length) {
        productForm.product_list = skus.map(item => {
          return {
            warning_value: item.warning_value,
            unit: item.unit,
            specs: item.spec_list
          }
        })
      }
      if (!productForm.have_spec) {
        productForm.product_list = [{
          unit: productForm.unit,
          warning_value: productForm.warning_value
        }]
      }
      const updateProduct = this.goodsId ? API_BasicSetting.editProduct(this.goodsId, productForm) : API_BasicSetting.addProduct(productForm)
      updateProduct.then(res => {
        this.$message.success(`商品${this.goodsId ? '修改' : '添加'}成功！`)
        const { callback } = this.$route.params
        if (typeof callback === 'function') callback()
        this.$store.dispatch('delCurrentViews', {
          view: this.$route,
          $router: this.$router
        })
        this.$router.push({ name: 'productFile' })
      })
    },
    // 获取商品详情信息
    async GET_GoodData() {
      try {
        API_BasicSetting.getGoodsInfo(this.goodsId).then(res => {
          res.product_list.map(item => {
            item.spec_list = item.specs
          })
          this.productForm = res
          this.$set(this.productForm, 'unit', res.product_list[0].unit)
          this.$set(this.productForm, 'warning_value', res.product_list[0].warning_value)
        })
      } catch (e) {
        //
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bg-in {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.content-goods-sku {
  border-bottom: 1px solid #dcdfe6;

  div.base-info-item>div {
    margin-left: 5%
  }

  div.base-info-item {
    h4 {
      margin-bottom: 10px;
      padding: 0 10px;
      border: 1px solid #ddd;
      background-color: #f8f8f8;
      font-weight: bold;
      color: #333;
      font-size: 14px;
      line-height: 40px;
      text-align: left;
    }

    .el-form-item {
      width: 50%;
      display: flex;

      .goods-image-list {
        width: 148px;
        height: 148px;
        overflow: hidden;
        margin: 0 8px 8px 0;
        border-radius: 6px;
        border: 1px solid #c0ccda;
        box-sizing: border-box;
        display: inline-block;
        cursor: pointer;

        img {
          width: 148px;
          height: 148px;
        }
      }
    }

    /deep/ .el-form-item__content {
      flex: 1;
      margin-left: 0 !important;
    }
  }
}

.footer {
  padding: 20px 0;
  text-align: center;
}
</style>
