<style scoped>
.user-panel {
  margin: 10px auto;
}
</style>
<template>
  <el-dialog :visible.sync="showStockDialog" :title="title" append-to-body style="text-align: left" @close="closeDialog" :close-on-click-modal="false">
    <div class="user-panel" v-loading="loading">
      <el-form ref="form" :model="formModel" :rules="ruleValidate" :label-width="'100px'">
        <el-form-item label="名称" prop="ingredientName">
          {{formModel.ingredientName}}
        </el-form-item>
        <el-form-item label="最小库存" prop="minStock">
          <el-input-number v-model="formModel.minStock" :step="1" :min="0" step-strictly></el-input-number>
          {{formModel.unitName}}
        </el-form-item>
        <el-form-item label="最大库存" prop="maxStock">
          <el-input-number v-model="formModel.maxStock" :step="1" :min="0" step-strictly></el-input-number>
          {{formModel.unitName}}
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import Constant from "@/constant";
import inventoryApi from "@/api/base/inventory";

export default {
  props: ["stockKey", "title"],
  data() {
    return {
      formModel: {},
      ruleValidate: {
        minStock: [{ required: true, message: "最小库存不能为空", trigger: "blur" }],
        maxStock: [{ required: true, message: "最大库存不能为空", trigger: "blur" }],
      },
      showStockDialog: true,
      loading: false,
      submitting: false,
    };
  },
  methods: {
    closeDialog() {
      this.$emit("close", false);
    },
    handleSubmit() {
      var self = this;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          (function () {
            return inventoryApi.update(self.formModel);
          })().then(function (response) {
            var jsonData = response.data;

            if (jsonData.result) {
              self.$message({
                message: "保存成功!",
                type: "success",
              });

              self.$emit("close", true);
            } else {
              self.$message({
                message: jsonData.message + "",
                type: "warning",
              });

              self.$emit("close", false);
            }
          });
        }
      });
    },
  },
  mounted: function () {
    var self = this;

    (function () {
      return inventoryApi.edit(self.stockKey);
    })()
      .then((response) => {
        var jsonData = response.data;
        self.loading = false;

        if (jsonData.result) {
          self.formModel = jsonData.data;
        } else {
          self.$message.error(jsonData.message + "");
        }
      })
      .catch((error) => {
        self.$message.error(error + "");
      });
  },
};
</script>