<template>
  <div class="app-container">
    <el-row class="m-t-0">
      <el-col :span="24">
        <el-container>
          <el-header height="42px" class="l-h-42 p-l-10 p-r-10 border border-b-n">
            <div class="l">
              <i v-if="pageState === 'add'" class="el-icon-plus f-s-20"></i>
              <i v-else class="el-icon-edit f-s-20"></i>
              <font class="m-l-10 f-s-18 fb">{{ $route.meta.title }}</font>
            </div>
          </el-header>
          <el-main class="border p-20 m-b-20">
            <el-form ref="form" :model="form" label-width="120px" :label-position="$store.state.app.isWideScreen?'top':'right'">
              <el-form-item v-if="pageState === 'add'" label="所属商铺">
                <SelectionShopId v-model="form.shop_id" />
              </el-form-item>
              <el-form-item label="单品名称">
                <el-input v-model="form.name" placeholder="单品名称" />
              </el-form-item>
              <el-form-item label="编号">
                <el-input v-model="form.sku_number" placeholder="单品编号，方便统筹" />
              </el-form-item>
              <el-form-item label="计量单位">
                <el-input v-model="form.unit" placeholder="计量单位。例如：件 瓶等..." />
              </el-form-item>
              <el-form-item label="价格">
                <el-input v-model="form.price" placeholder="单品的价格，可精确到小数点后两位。例如：3.14">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="重量">
                <el-input v-model="form.weight" placeholder="单品重量">
                  <template slot="append">克</template>
                </el-input>
              </el-form-item>
              <el-form-item label="库存量">
                <el-input v-model="form.stock" placeholder="如果此商品没有库存管理的需求，此值尽量设的大一些。例如：99999" />
              </el-form-item>
              <!-- 商品图片 -->
              <el-form-item label="商品图片">
                <el-upload class="avatar-uploader" drag name="file" :action="action" :headers="myheader"
                  :show-file-list="false" :on-success="handleUpSuccess" :on-error="handleUpErr"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="form.upFile != ''"
                    :src="$store.state.settings.host + '/Data/UploadFiles/temp/' + form.upFile" class="avatar" />
                  <img v-else-if="form.oldFile != [] && form.upFile == ''"
                    :src="form.oldFile[0]" class="avatar" />
                  <template v-else>
                    <i class="el-icon-plus f-s-30 m-t-70 seatFontColor"></i>
                    <div class="el-upload__text"><em>建议400*400像素 <br> jpg png </em></div>
                  </template>
                </el-upload>
              </el-form-item>
              <!-- 采购渠道 -->
              <el-form-item label="采购渠道">
                <el-input v-model="form.purchase_channel" maxlength="150" show-word-limit type="textarea"
                  placeholder="记录采购的渠道。电话，地址等..." />
              </el-form-item>
              <!-- 表单提交 -->
              <el-form-item v-if="pageState == 'add' ? true : false">
                <el-button type="primary" icon="el-icon-plus" @click="addSku">创建</el-button>
                <el-button @click="setForm({ shop_id: form.shop_id, oldFile: '' })" class="iconfont icon-qingchu">
                  <font class="m-l-5">重填</font>
                </el-button>
              </el-form-item>
              <el-form-item v-else>
                <el-button type="primary" icon="el-icon-edit" @click="saveSku">更新</el-button>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import SelectionShopId from '@/components/SelectionShopId'

export default {
  name: 'SkuAdd',
  data () {
    return {
      action: this.$store.state.settings.baseURL + this.$store.state.settings.apiAdminPath + 'upImgFile',
      myheader: { token: this.$store.state.user.token },
      form: {
        shop_id: '',
        name: '',
        sku_number: '',
        price: '',
        unit: '',
        weight: '',
        stock: '',
        purchase_channel: '',
        upFile: '',
        oldFile: ''
      },
      skuId: this.$route.params.id, // get参数 获取商品id 没有为添加页面
      pageState: 'add', // 页面状态
      sku: null
    }
  },
  components: {
    SelectionShopId
  },
  computed: {
    // 获取商品列表
    skuList () {
      return this.$store.state.skuList
    }
  },
  methods: {
    /* 文件上传表单 */
    handleUpSuccess (res) {
      if (res.status === 0) {
        this.$message.error(res.msg)
      } else {
        this.form.upFile = res.data
        this.$message.success(res.msg)
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isJPG) {
        this.$message.error('上传图片只能是JPG|PNG|GIF格式!')
      }
      return isJPG
    },
    handleUpErr () {
      this.$message.error('接口访问失败')
    },
    // 设置表单
    setForm (data) {
      this.form.shop_id = data.shop_id
      this.form.name = data.name
      this.form.sku_number = data.sku_number
      this.form.price = data.price
      this.form.unit = data.unit
      this.form.weight = data.weight
      this.form.stock = data.stock
      this.form.purchase_channel = data.purchase_channel
      this.form.oldFile = data.oldFile
      if (Object.keys(data).length === 0) {
        this.$message.warning('清空表单')
      }
    },
    // 初始化页面 添加or编辑
    initPage () {
      if (this.skuId === undefined) {
        this.pageState = 'add'
      } else {
        this.pageState = 'edit'
        this.sku = this.skuList.find((item) => item.id === this.skuId)
        if (this.sku) {
          const data = {
            shop_id: this.sku.shop_id,
            name: this.sku.name,
            sku_number: this.sku.sku_number,
            price: this.sku.price,
            unit: this.sku.unit,
            weight: this.sku.weight,
            stock: this.sku.stock,
            purchase_channel: this.sku.purchase_channel,
            oldFile: this.sku.photo
          }
          this.setForm(data)
        }
      }
    },
    /**
     * @description: 创建新商品sku
     */
    async addSku () {
      const res = await this.$store.dispatch('fetchAddSku', this.form)
      if (res.data.status === 1) {
        this.$router.push('/sku/index')
      }
    },
    /**
     * @description: 更新商品sku
     */
    async saveSku () {
      this.form.id = this.skuId
      const res = await this.$store.dispatch('fetchSaveSku', this.form)
      if (res.data.status === 1) {
        this.$router.push('/sku/index')
      }
    }
  },
  watch: {
    skuList () {
      this.initPage()// 初始化页面
    }
  },
  created () {
    if (this.skuList.length > 0) {
      this.initPage()// 初始化页面
    }
  }
}
</script>

<style scoped>
.line {
  text-align: center;
}

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

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

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

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

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

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

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

.el-upload__text {
  line-height: 1.2em !important;
}
</style>
