<template>
  <a-card :bordered="false" class="goodsEdit-table-page-wrapper">
    <a-form
      id="goodsEdit-form"
      :form="form"
      ref="form"
      v-bind="formItemLayout"
      @submit="handleSubmit">
      <a-form-item label="首页图" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <Upload
          class="upload"
          id="goodsEdit-homeImage"
          v-decorator="[ 'formData.homeImage', { initialValue: formData.homeImage, rules: [{ required: true, message: '请上传首页图' }] } ]"
          ref="homeImage"
          :fileSize="0.25"
          @change="changeHomeImage"
          listType="picture-card" ></Upload>
        <span class="upload-desc">请上传325*250尺寸的图片，大小不超过0.25MB，png、jpg、jpeg格式。</span>
      </a-form-item>
      <a-form-item label="商品图片" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <Upload
          class="upload"
          id="goodsEdit-images"
          v-decorator="[ 'formData.images', { initialValue: formData.images, rules: [{ required: true, message: '请上传商品图片' }] } ]"
          ref="goodsImage"
          :maxNums="6"
          :fileSize="0.25"
          @change="changeImage"
          listType="picture-card" ></Upload>
        <span class="upload-desc">请上传750*325尺寸的图片，大小不超过0.25MB，png、jpg、jpeg格式。（最多可上传6张）</span>
      </a-form-item>
      <a-form-item label="商品名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input
          id="goodsEdit-name"
          :maxLength="30"
          v-decorator="[
            'formData.name',
            { initialValue: formData.name, getValueFromEvent: $filterEmpty, rules: [{ required: true, message: '请输入商品名称(最多30个字符)' }] }
          ]"
          placeholder="请输入商品名称(最多30个字符)"
          allowClear />
      </a-form-item>
      <a-form-item label="商品分类" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="goodsEdit-goodsTypeNo"
          allowClear
          v-decorator="[
            'formData.goodsTypeNo',
            { initialValue: formData.goodsTypeNo,
              rules: [{ required: true, message: '请选择商品分类' }] },
          ]"
          placeholder="请选择商品分类">
          <a-select-option v-for="(item,index) in goodsTypeList" :key="index" :value="item.goodsTypeNo" :disabled="item.state==0">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="商品价格" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input-number
          id="goodsEdit-sellGold"
          class="inpNumber-unit"
          :min="0"
          :max="999999"
          :precision="0"
          v-decorator="[ 'formData.sellGold', { initialValue: formData.sellGold, rules: [{ required: true, message: '请输入商品价格(0~999999)' }] } ]"
          placeholder="请输入商品价格(0~999999)。10个乐豆等值于1元"
          allowClear />
        <span class="inp-unit">乐豆</span>
      </a-form-item>
      <a-form-item label="商品状态" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" v-if="!isEdit">
        <v-select
          ref="state"
          code="GOODS_STATE"
          allowClear
          id="goodsEdit-state"
          placeholder="请选择商品状态"
          v-decorator="['formData.state', { initialValue: formData.state, rules: [
            { required: true, message: '请选择商品状态' },
            { validator: stateValidator }
          ] }]"
        ></v-select>
      </a-form-item>
      <a-form-item label="库存数量" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-input-number
          id="goodsEdit-inventoryQty"
          class="inpNumber"
          :min="0"
          :max="999999"
          :precision="0"
          v-decorator="['formData.inventoryQty', { initialValue: formData.inventoryQty, rules: [
            { required: true, message: '请输入库存数量' },
            { validator: inventoryQtyValidator }
          ] }]"
          placeholder="请输入库存数量(0~999999)。当库存数量为0时显示为已售罄且无法下单"
          allowClear />
      </a-form-item>
      <a-form-item label="供货商" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <a-select
          id="goodsEdit-officialPartnerNo"
          allowClear
          :disabled="isEdit"
          v-decorator="[
            'formData.officialPartnerNo',
            { initialValue: formData.officialPartnerNo,
              rules: [{ required: true, message: '请选择供货商' }] },
          ]"
          placeholder="请选择供货商">
          <a-select-option v-for="(item,index) in partnerList" :key="index" :value="item.officialPartnerNo" :disabled="item.state==0">{{ item.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="商品详情" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
        <editor id="goodsEdit-editor" ref="editor" class="goodsEdit-editor" @on-change="editorChange" :cache="false"></editor>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
        <a-button type="primary" html-type="submit" id="goodsEdit-btn-submit" style="margin-right: 15px">保存</a-button>
        <a-button @click="close" style="margin-left: 15px" id="goodsEdit-btn-close">取消</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import { Upload, STable, VSelect } from '@/components'
import Editor from '@/components/WEeditor'
import { goodsTypeQueryList } from '@/api/goodsType'
import { supplierQueryList } from '@/api/supplier'
import { goodsSave, goodsFind } from '@/api/goods'
export default {
  name: 'GoodsEdit',
  components: { Upload, STable, VSelect, Editor },
  data () {
    return {
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      formData: {
        homeImage: '', //  首页图
        images: '', //  商品图
        name: '', // 商品名称
        goodsTypeNo: undefined, // 商品分类
        sellGold: '', //  商品价格
        state: '', //  商品状态
        inventoryQty: '', // 库存数量
        officialPartnerNo: undefined, //  供货商
        desc: null //  商品详情
      },
      goodsTypeList: [], //  商品分类下拉数据
      partnerList: [] //  供应商下拉数据
    }
  },
  computed: {
    isEdit () {
      return this.$route.name === 'goodsListEdit'
    }
  },
  methods: {
    //  商品状态自定义校验
    stateValidator (rule, value, callback) {
      if (value == 1 && String(this.form.getFieldValue('formData.inventoryQty')) && this.form.getFieldValue('formData.inventoryQty') == 0) {
        callback(new Error('库存为0的商品不能上架'))
      } else {
        callback()
      }
    },
    //  输入库存数量调起商品状态校验
    inventoryQtyValidator (rule, value, callback) {
      this.form.validateFields(['formData.state'], (errors, values) => {
        if (!errors) {
          callback()
        }
      })
    },
    //  获取商品详情
    getGoodsDetail () {
      goodsFind({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.formData = Object.assign(this.formData, res.data)
          this.$refs.homeImage.setFileList(res.data.homeImage)
          this.$refs.goodsImage.setFileList(res.data.images)
          this.$refs.editor.setHtml(this.formData.desc)
        }
      })
    },
    //  商品分类下拉数据
    getGoodsType () {
      goodsTypeQueryList({}).then(res => {
        if (res.status == 200) {
          this.goodsTypeList = res.data
        } else {
          this.goodsTypeList = []
        }
      })
    },
    //  供应商下拉数据
    getPartnerQueryList () {
      supplierQueryList({}).then(res => {
        if (res.status == 200) {
          this.partnerList = res.data
        } else {
          this.partnerList = []
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          const formData = values.formData
          formData.desc = _this.formData.desc
          formData.id = this.isEdit ? this.$route.params.id : null
          goodsSave(formData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.$router.push({ path: '/shop/goods/list' })
              }, 1000)
            }
          })
        }
      })
    },
    //  取消
    close () {
      this.$router.push({ path: '/shop/goods/list' })
    },
    //  商品图上传
    changeImage (file) {
      this.formData.images = file
    },
    //  首页图上传
    changeHomeImage (file) {
      this.formData.homeImage = file
    },
    //  商品详情  文本编辑器
    editorChange (html, text) {
      this.formData.desc = html
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getGoodsType()
      vm.getPartnerQueryList()
      if (vm.isEdit) { //  详情页
        vm.getGoodsDetail()
      }
    })
  }
}
</script>

<style lang="less">
  .goodsEdit-table-page-wrapper{
    .upload{
      width: 100%!important;
    }
    //  商品图片描述
    .upload-desc{
      font-size: 12px;
      color: #808695;
    }
    //  input-number 框宽度
    .inpNumber{
      width: 100%;
    }
    .inpNumber-unit{  //  有单位的
      width: 90%;
      margin-right: 8px;
    }
    //  文本编辑器  工具栏样式换行
    .goodsEdit-editor{
      .w-e-toolbar{
        flex-wrap: wrap;
      }
    }
  }
</style>
