<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" width="480" :close-on-click-modal="false" @closed="$emit('closed')">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <el-form-item v-if="$store.state.tenant.tenantId === '0'" label="所属租户" prop="tenantId">
                <el-select v-if="!form.id" v-model="form.tenantId" filterable placeholder="请选择所属租户">
                    <el-option v-for="item in $store.state.tenant.tenants" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
                <el-input v-else v-model="tenantName" readonly></el-input>
			</el-form-item>
            <el-form-item label="仓库名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入仓库名称"></el-input>
            </el-form-item>
            <el-form-item label="仓库编号" required>
                <el-input v-model="form.code" :readonly="!!form.id" maxlength="50" show-word-limit clearable placeholder="不填将自动生成"></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button auto-insert-space @click="visible = false">取消</el-button>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit">保存</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import XEUtils from "xe-utils";

import API from "@/api";
import store from "@/store";
const $emit = defineEmits(["success", "closed"]);
const visible = ref(false);
const isSaving = ref(false);

const mode = ref("add");
const titleMap = reactive({
    add: "新增仓库",
    edit: "修改仓库"
});

const tenantName = computed(() => XEUtils.get(XEUtils.find(store.state.tenant.tenants, item => item.id == form.value.tenantId), "name"));
const form = ref({
    id: null,
    tenantId: store.state.tenant.tenantId,
    name: null,
    code: null
});
const rules = reactive({
    tenantId: [{ required: true, message: "请选择所属租户" }],
    name: [{ required: true, message: "请输入仓库名称" }]
});

const open = () => visible.value = true;
const setData = data => {
    open();
    mode.value = "edit";
    XEUtils.objectEach(form.value, (_, key) => XEUtils.set(form.value, key, XEUtils.get(data, key)));
}

const formRef = ref();
const submit = () => {
    formRef.value.validate(valid => {
        if (valid) {
            isSaving.value = true;
            API.basic.warehouse[mode.value](form.value).then(res => {
                isSaving.value = false;
                ElMessage.success("操作成功");
                visible.value = false;
                $emit("success", mode.value);
            }).catch(() => isSaving.value = false);
        } else {
            return false;
        }
    });
}

defineExpose({
    open,
    setData
});
</script>

<style scoped>
.el-form {padding-right: 34px;}
</style>