<template>
  <el-dialog
    :visible.sync="modalIsShow"
    title="选择批次号"
    top="10vh"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="dialogOpened"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      label-width="70px"
    >
      <el-form-item prop="sequence" label="批次号：">
        <el-input
          v-model.trim="modalForm.alphabet"
          placeholder="编码"
          disabled
          style="width: 80px"
        >
        </el-input>
        <el-input-number
          v-model="modalForm.sequence"
          placeholder="请输入"
          :min="1"
          :max="999999"
          :step="1"
          step-strictly
          :controls="false"
        ></el-input-number>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
const initModalForm = { alphabet: "A", sequence: 1 };

export default {
  name: "select-batch-no-dialog",
  data() {
    return {
      modalIsShow: false,
      modalForm: { ...initModalForm },
      rules: {
        sequence: [
          {
            required: true,
            message: "请输入批次号",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    dialogOpened() {
      const batchInfo = this.$ls.get("batchInfo");
      if (batchInfo) {
        this.modalForm.alphabet = batchInfo.alphabet;
        this.modalForm.sequence = batchInfo.sequence + 1;
      } else {
        this.modalForm = { ...initModalForm };
      }

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
      });
    },
    async confirm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      const batchNo = `${this.modalForm.alphabet}${this.modalForm.sequence}`;

      this.$ls.set("batchInfo", {
        ...this.modalForm,
        batchNo,
      });
      this.$emit("confirm", batchNo);
      this.cancel();
    },
  },
};
</script>
