<template>
  <div>
    <el-dialog :title="exData.id ? '编辑': '新增'"
               :visible.sync="dialog"
               width="50%"
               :close-on-click-modal="false"
               top="50px">
      <el-form ref="form"
               :model="form"
               :rules="formRules"
               label-width="120px">
        <!--        <el-form-item prop="storage_name"-->
        <!--                      :rules="formRules.required"-->
        <!--                      label="酒名：">-->
        <!--          <el-input v-model="form.storage_name"-->
        <!--                    placeholder="请输入酒名"-->
        <!--                    clearable></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item prop="storage_name" :rules="formRules.required" label="酒名：">
          <el-select
            v-model="form.storage_name"
            filterable
            remote
            reserve-keyword
            :remote-method="myFilterOfRule"
            @visible-change="getDropdownOfRule($event)"
            :loading="loading">
            <el-option
              v-for="item in getMyFilterGoodsInfo"
              :key="item.index"
              :label="item.storage_name"
              :value="item.id">
              <p>商品名称</p>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="storage_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="user_phone"
                      :rules="formRules.mobile"
                      label="用户手机号：">
          <el-input v-model="form.user_phone"
                    placeholder="请输入用户手机号"
                    @input="form.user_phone = form.user_phone.replace(/[^\d]/g, '').slice(0, 11)"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="user_name"
                      :rules="formRules.required"
                      label="用户昵称：">
          <el-input v-model="form.user_name"
                    placeholder="请输入用户昵称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item prop="storage_status"
                      :rules="formRules.required"
                      label="状态：">
          <el-radio v-model="form.storage_status"
                    label="0">存酒中
          </el-radio>
          <el-radio v-model="form.storage_status"
                    label="1">已取
          </el-radio>
        </el-form-item>
        <el-form-item prop="storage_remark"
                      label="备注：">
          <el-input v-model="form.storage_remark"
                    type="textarea"
                    rows="6">
          </el-input>
        </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 getCode from '@/views/ums/mixin/getCode'

export default {
  mixins: [getCode],
  components: {},
  props: {
    value: {
      type: Boolean,
      default: true
    },
    exData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data () {
    return {
      dialog: !!this.value,
      form: {
        storage_name: '', // 酒名
        storage_img_url: [], // 存酒图片
        user_phone: '', // 用户手机号码
        user_name: '', // 用户姓名
        storage_status: '1', // 存酒状态(0存酒中1已取出)
        storage_remark: '' // 存酒备注
      },
      fileList: [],
      booLock: false,
      getMySearchInfo: '',
      getMyFilterGoodsInfo: [],
      loading: 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.storage_img_url = this.form.storage_img_url.filter(item => item !== path)
    },
    handleAvatarSuccess (res) {
      if (res.code === 200) {
        const { path } = res.data
        this.form.storage_img_url.push(path)
      } else {
        this.$message.error('图片上传失败')
      }
    },
    hadnleExceed (files, fileList) {
      this.$message({
        message: '商品图最多上传一张',
        type: 'warning'
      })
    },
    handleSubmit () {
      const url = this.exData.id ? '/v1/user/storage/modify' : ''
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.booLock = true
          const data = await this.$fetch(url, {
            ...this.form,
            storage_img_url: this.form.storage_img_url[0]
          })
          this.booLock = false
          if (data.code === 200) {
            this.$message.success('提交成功')
            this.$emit('success')
            this.dialog = false
          }
        }
      })
    },
    getDropdownOfRule (e) {
      if (e === true) {
        this.myFilterOfRule(this.getMySearchInfo)
      } else {
        const _result = this.getMyFilterGoodsInfo.filter(item => item.id === this.form.id || item.storage_name === this.getMySearchInfo)
        if (_result.length) {
          this.getMySearchInfo = _result[0].id
          this.form.storage_name = _result[0].storage_name
        } else {
          this.getMySearchInfo = ''
          this.form.id = ''
        }
        this.getMyFilterGoodsInfo = []
      }
    },
    myFilterOfRule (query) {
      this.getMySearchInfo = query
      if (query !== '') {
        this.loading = true
        this.$set(this.form, 'storage_name', query)
        setTimeout(async () => {
          this.loading = false
          const data = await this.$fetch('', {
            storage_name: '商品名称'
          })

          this.getMyFilterGoodsInfo = res.data
        }, 200)
      } else {
        this.getMyFilterGoodsInfo = []
      }
    },
  },
  mounted () {
    if (this.exData.id) {
      this.$set(this.form, 'id', this.exData.id)
      this.fileList = [
        {
          name: '',
          url: this.exData.storage_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 === 'storage_img_url') {
              value = [value]
            }
            if (key === 'storage_status') {
              value = value.toString()
            }
            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;
}
</style>
