<template>
  <el-dialog class="dialog"
             :visible.sync="dialogVisible"
             center
             title="出库"
             append-to-body
             :before-close="onBeforeClose"
             @close="onClose"
             width="500px">
    <el-form label-width="100px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="物品名称">
        <el-input v-model="data.name" class="input-width" disabled></el-input>
      </el-form-item>
      <el-form-item label="物品数量" prop="count">
        <el-input v-model="dataForm.count" class="input-width" oninput="value=value.replace(/[^\d]/g,'')">
          <template slot="append">台</template>
        </el-input>
      </el-form-item>
      <el-form-item label="领取人" prop="username">
        <el-autocomplete
            class="input-width"
            v-model="dataForm.username"
            :fetch-suggestions="queryUserWithName"
            placeholder="请输入用户姓名搜索用户"
            :trigger-on-focus="false"
            @change="onUserChange"
            @select="onUserSelect"
        ></el-autocomplete>
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="onConfirm">确 认</el-button>
      <el-button @click="onCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";

export default {
  name: "assetsGoodsDialogTake",
  components: {},
  props: {
    visible: {
      type: Boolean
    },
    data: {
      type: Object
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  data() {
    const validateCount = (rule, value, callback) => {
      if (rule.required) {
        if (!value || value.length === 0) {
          callback(new Error('物品数量不能为空'));
        } else if (Number(value) > this.data.count) {
          callback(new Error('物品数量不能超过库存数'));
        }
      }
      callback();
    };
    return {
      dataForm: {
        id: undefined, // 物品id
        count: undefined, // 变化数量，入库时大于0，出库时小于0
        userId: undefined, // 领取人id
      },

      dataRules: {
        count: [{validator: validateCount, required: true, trigger: 'change'}],
        username: [{validator: validateNotEmpty, errorMessage: "领取人不能为空", required: true, trigger: 'blur'}]
      }
    }
  },

  mounted() {
    this.dataForm.id = this.data.id;
    this.dataForm.name = this.data.name;
  },

  methods: {
    // 根据名称搜索用户
    queryUserWithName(queryString, cb) {
      this.$axios.get("/v1/system/user/list/option", {params: {keyword: queryString, page: 1, size: 10}}, false).then((data) => {
        const userList = data.map(item => {
          return {
            value: item.name, // 用于显示
            id: item.id
          }
        });
        cb(userList);
      })
    },

    onUserChange() {
      this.dataForm.userId = undefined;
    },

    onUserSelect(user) {
      this.dataForm.userId = user.id;
    },

    // 取消
    onCancel() {
      this.dialogVisible = false;
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate().then(valid => {
        if (valid) {
          this.$axios.put("/v1/stock/goods/take", this.dataForm).then(() => {
            this.$message.success("出库成功！");
            this.$emit("update");
            this.onCancel();
          });
        }
      })
    },

    // 关闭前确认
    onBeforeClose(done) {
      if (this.$store.state.app.closeConfirmEnable) {
        this.$confirm("确认关闭？").then(() => done());
      } else {
        done();
      }
    },

    // 关闭
    onClose() {
      this.$emit("close");
    }
  }
}
</script>

<style scoped lang="scss">
.input-width {
  width: 300px;
}
</style>
