<template>
  <div>
    <el-dialog :title="exData.id ? '编辑': '新增'"
               :visible.sync="dialog"
               width="900px"
               :close-on-click-modal="false"
               top="50px">
      <el-form ref="form"
               :model="form"
               :rules="formRules"
               label-width="120px">
        <el-form-item
          prop="category_id"
          :rules="rules.categoryId"
          label="商品分类：">
          <el-select
            style="width: 100%;"
            v-model="form.category_id"
            filterable
            clearable
            placeholder="请选择">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.category_name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="product_name"
                      :rules="formRules.required"
                      label="商品名称：">
          <el-input v-model="form.product_name"
                    placeholder="请输入商品名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="product_img_url"
                      :rules="formRules.uploadImgs"
                      label="图片：">
          <el-upload :on-remove="handleRemove"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload"
                     :on-exceed="hadnleExceed"
                     :accept="'image/*'"
                     :limit="1"
                     :file-list="fileList"
                     list-type="picture-card"
                     action="/api/admin/v1/upload/file"
                     multiple>
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="product_place"
                      :rules="formRules.required"
                      label="出单位置：">
          <el-select style="width: 100%;" v-model="form.product_place" placeholder="请选择">
            <el-option
              v-for="item in [{id: '1', name: '厨房'},{id: '2', name: '柜台'}]"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="product_status"
                      :rules="formRules.required"
                      label="是否上架：">
          <el-radio v-model="form.product_status"
                    label="1">上架
          </el-radio>
          <el-radio v-model="form.product_status"
                    label="0">下架
          </el-radio>
        </el-form-item>
        <el-form-item prop="product_is_storage"
                      :rules="formRules.required"
                      label="是否支持存酒：">
          <el-radio v-model="form.product_is_storage"
                    label="1">支持
          </el-radio>
          <el-radio v-model="form.product_is_storage"
                    label="0">不支持
          </el-radio>
        </el-form-item>
        <el-form-item prop="product_desc"
                      label="商品描述：">
          <tinymce :height="300" v-model="form.product_desc"/>
        </el-form-item>
        <el-form-item label="设置SKU"></el-form-item>
        <el-form-item v-for="(sku, index) in form.skus"
                      :label="'SKU' + (index + 1)"
                      :key="index"
                      :prop="'skus.' + index + '.product_sku'"
                      :rules="rules.sku">
          <el-col :span="9">
            <el-input v-model="sku.product_sku" placeholder="请设置SKU名"></el-input>
          </el-col>
          <el-col :span="6">
            <el-input v-model="sku.product_price"
                      placeholder="请输入单价"
                      @input="sku.product_price=sku.product_price.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                      clearable></el-input>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-switch
              v-model="sku.product_status"
              active-text="上架"
              inactive-text="下架">
            </el-switch>
          </el-col>
          <el-col :span="3">
            <el-button type="warning"
                       size="small"
                       :disabled="form.skus.length <= 1"
                       @click.prevent="removeSku(sku)">删除
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click.prevent="addSku">新增SKU</el-button>
        </el-form-item>
        <el-form-item label="设置可选规格"></el-form-item>
        <el-form-item v-for="(attr, index) in form.attachs"
                      :key="'a' + index"
                      :label="'附加' + (index + 1)"
                      :prop="'attachs.' + index + '.attach_name'"
                      :rules="rules.attach">
          <el-col :span="6">
            <el-select
              v-model="attr.attach_name"
              filterable
              allow-create
              default-first-option
              @change="handleChange($event, index)"
              placeholder="请选择附加名"
              style="width: 100%;">
              <el-option
                v-for="item in goodsAttrData"
                :key="item.id"
                :label="item.attach_name"
                :value="item.attach_name">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="10">
            <el-select
              v-model="attr.attach_content"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择附加明细"
              style="width: 100%;">
              <el-option
                v-for="(item, idx) in setAttachContentOptions(attr.attach_name, goodsAttrData)"
                :key="idx"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-input type="number"
                      v-model="attr.attach_max_num"
                      placeholder="最多可选数量"></el-input>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-button type="warning"
                       size="small"
                       :disabled="form.attachs.length <= 1"
                       @click.prevent="removeAttach(attr)">删除
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button size="small"
                     @click.prevent="addAttach">添加规格
          </el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-center">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" :disabled="booLock" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tinymce from '@/components/Tinymce/index.vue'
import { yuan2Fen, fen2Yuan } from '@/utils'

export default {
  components: {
    tinymce
  },
  props: {
    value: {
      type: Boolean,
      default: true
    },
    exData: {
      type: Object,
      default: function () {
        return {}
      }
    },
    categoryData: {
      type: Array,
      default: function () {
        return []
      }
    },
    goodsAttrData: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    const checkProductPrice = (rule, value, callback) => {
      const index = rule.field.replace(/\w*\./, '').replace(/\.\w*/, '')
      const productStock = this.form.skus[index * 1].product_stock
      const productPrice = this.form.skus[index * 1].product_price
      if (value && productStock * 1 > 0 && productPrice) {
        callback()
      } else {
        if (!value) {
          callback(new Error('请设置SKU名'))
        }
        if (!productStock) {
          callback(new Error('请设置库存数量'))
        }
        if (!productPrice) {
          callback(new Error('请输入单价'))
        }
      }
    }

    const checkAttachContent = (rule, value, callback) => {
      const index = rule.field.replace(/\w*\./, '').replace(/\.\w*/, '')
      const attachContent = this.form.attachs[index * 1].attach_content
      const attachMaxNum = this.form.attachs[index * 1].attach_max_num * 1

      if ((value && attachContent.length && attachMaxNum > 0) || (!value && attachContent.length < 1)) {
        callback()
      } else {
        if (!value) {
          callback(new Error('请选择附加名'))
        }
        if (!attachContent.length) {
          callback(new Error('请选择附加明细'))
        }
        if (!attachMaxNum) {
          callback(new Error('请输入最多可选数量'))
        }
      }
    }

    return {
      dialog: !!this.value,
      form: {
        category_id: '', // 分类ID
        product_name: '', // 商品名称
        product_img_url: [], // 商品图片，只上传一张图
        product_place: '1', // 出单位置(1厨房2柜台)
        product_status: '1', // 商品状态(0无效1有效)
        product_is_storage: '1', // 是否支持存酒 0不支持 1支持
        product_desc: '', // 商品描述(富文本编辑器)
        skus: [
          {
            product_sku: '', // sku规格
            product_stock: 100, // 商品库存
            product_status: true, // 商品状态(0下架1上架)
            product_price: '' // 商品价格
          }
        ], // 商品sku
        attachs: [
          {
            attach_name: '', // 规格名称
            attach_content: [], // 附加选项(以逗号隔开)
            attach_max_num: 1
          }
        ] // 规格
      },
      rules: {
        categoryId: [{ required: true, message: '请选择商品分类', trigger: ['blur', 'change'] }],
        sku: [{ required: true, validator: checkProductPrice, trigger: 'blur' }],
        attach: [{ validator: checkAttachContent, trigger: ['blur', 'change'] }]
      },
      fileList: [],
      booLock: false
    }
  },
  methods: {
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isLt2M
    },
    handleRemove (file) {
      let path = file.url
      if (file.response && file.response.data) {
        path = file.response.data.path
      }
      this.form.product_img_url = this.form.product_img_url.filter(item => item !== path)
    },
    handleAvatarSuccess (res) {
      if (res.code === 200) {
        const { path } = res.data
        this.form.product_img_url.push(path)
      } else {
        this.$message.error('图片上传失败')
      }
    },
    hadnleExceed (files, fileList) {
      this.$message({
        message: '商品图最多上传一张',
        type: 'warning'
      })
    },
    removeSku (item) {
      var index = this.form.skus.indexOf(item)
      if (index !== -1) {
        this.form.skus.splice(index, 1)
      }
    },
    addSku () {
      this.form.skus.push({
        product_sku: '',
        product_stock: 100,
        product_status: true,
        product_price: ''
      })
    },
    removeAttach (item) {
      var index = this.form.attachs.indexOf(item)
      if (index !== -1) {
        this.form.attachs.splice(index, 1)
      }
    },
    addAttach () {
      this.form.attachs.push({
        attach_name: '',
        attach_content: [],
        attach_max_num: 1
      })
    },
    setAttachContentOptions (name, arr) {
      const index = arr.findIndex(item => item.attach_name === name)
      if (index < 0) {
        return []
      }
      return arr[index].attach_content.split(',')
    },
    handleChange (val, index) {
      this.$set(this.form.attachs[index], 'attach_content', [])
    },
    handleSubmit () {
      const url = this.exData.id ? '/v1/bar/product/modify' : '/v1/bar/product/add'
      this.$refs.form.validate(async valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          const postData = {
            ...formData,
            product_img_url: formData.product_img_url[0],
            skus: formData.skus.map(item => ({
              ...item,
              product_status: item.product_status ? '1' : '0',
              product_price: yuan2Fen(item.product_price)
            })),
            // 非必填项，没值得时候默认传空数组
            attachs: formData.attachs[0].attach_name ? formData.attachs.map(item => ({
              ...item,
              attach_content: item.attach_content.join(',')
            })) : []
          }
          this.booLock = true
          const data = await this.$fetch(url, postData)
          this.booLock = false
          if (data.code === 200) {
            this.$message.success('提交成功')
            this.$emit('success')
            this.$store.dispatch('common/fetchGoodsArr')
            this.dialog = false
          }
        }
      })
    }
  },
  mounted () {
    if (this.exData.id) {
      this.$set(this.form, 'id', this.exData.id)
      this.fileList = [
        {
          name: '',
          url: this.exData.product_img_url
        }
      ]
      for (const key in this.exData) {
        if (this.form.hasOwnProperty(key)) {
          let value = this.exData[key]
          if ((Array.isArray(value) && value.length >= 1) || (Object.prototype.toString.call(value) === '[object Object]') || (typeof value === 'string' && value) || typeof value === 'number') {
            if (key === 'product_img_url') {
              value = [value]
            }
            if (key === 'product_place' || key === 'product_status' || key === 'product_is_storage') {
              value = value.toString()
            }
            if (key === 'skus') {
              value = value.map(item => ({
                ...item,
                product_status: item.product_status === 1,
                product_price: fen2Yuan(item.product_price)
              }))
            }
            if (key === 'attachs') {
              value = value.map(item => ({
                ...item,
                attach_content: item.attach_content.split(',')
              }))
            }
            this.$set(this.form, key, value)
          }
        }
      }
    }
  },
  watch: {
    dialog (val) {
      if (!val) this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
.top-tip {
  margin-top: -20px;
  margin-bottom: 20px;
}

.af-put-line-radio {
  display: flex;
  align-items: center;

  p.lalel {
    padding: 0 10px;
  }

  p {
    padding: 0;
    margin: 0;
  }
}
</style>
