<template>
  <el-dialog :title="title" :visible.sync="show" width="500px" center @open="open" @opened="opened" @close="close">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="SN码" prop="sn">
        <el-input
          ref="sn"
          maxlength="100"
          show-word-limit
          v-model="form.sn"
          placeholder="请输入SN码，或使用扫码枪获取"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="success" icon="el-icon-check" plain @click="handleSubmit" v-loading="loading">确认</el-button>
      <el-button icon="el-icon-close" plain @click="handleCancel" v-loading="loading">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'SnInput',
  props: {
    title: {
      type: String,
      default: '输入SN',
    },
    show: {
      type: Boolean,
      default: false,
    },
    requiredSn: {
      type: Boolean,
      default: true,
    },
    reset: {
      type: Boolean,
      default: true,
    },
    loading: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      form: {},
      rules: {
        sn: [
          {required: this.requiredSn, message: 'SN不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.resetForm();
  },
  methods: {
    opened() {
      this.$refs.sn.focus();
    },
    open() {
      if (this.reset) {
        this.resetForm();
      }
    },
    close() {
      this.$emit('update:show', false);
    },
    resetForm() {
      this.form = {
        sn: null,
      }
    },
    handleCancel() {
      this.$emit('cancel', this.form);
      this.close();
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('submit', this.form);
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">

</style>
