<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" fullscreen :close-on-click-modal="false" @closed="$emit('closed')">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <el-collapse v-model="activeNames">
                <el-collapse-item title="基本信息" name="basic">
                    <el-row>
                        <el-col v-if="$store.state.tenant.tenantId === '0'" :md="8" :xs="24">
                            <el-form-item 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-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="物料名称" prop="name">
                                <el-input v-model="form.name" placeholder="请输入物料名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <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-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="物料类型" prop="materialType">
                                <el-select v-model="form.materialType" clearable placeholder="请选择物料类型">
                                    <el-option v-for="(label, key) in materialDic.type" :key="key" :label="label" :value="key" :disabled="materialOptionDisabled(key)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="物料来源" prop="needType">
                                <el-select v-model="form.needType" clearable placeholder="请选择物料来源">
                                    <el-option v-for="(label, key) in materialDic.needType" :key="key" :label="label" :value="key" :disabled="needTypeOptionDisabled(key)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="规格型号">
                                <el-input v-model="form.specification" clearable placeholder="请输入规格型号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :md="8" :xs="24">
                            <el-form-item label="单位" prop="unit">
                                <el-select v-model.trim="form.unit" filterable :filter-method="filterMethod" placeholder="请选择物料单位">
                                    <el-option v-for="(label, key) in filterOptions" :key="key" :label="label" :value="key">
                                        <span style="float: left;">{{ label }}</span>
                                        <span style="float: right;padding-left: 18px;font-size: 13px;color: var(--el-text-color-secondary);">{{ key }}</span>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="isSalable" :md="8" :xs="24">
                            <el-form-item label="标准售价" prop="price">
                                <el-input-number v-model="form.price" :min="0" :precision="2" :controls="false" placeholder="请输入标准售价">
                                    <template #suffix>元</template>
                                </el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-collapse-item>
                
                <el-collapse-item title="其他说明" name="other">
                    <el-row>
                        <el-col :xs="24">
                            <el-form-item label="备注" label-width="100">
                                <el-input v-model="form.remark" type="textarea" maxlength="200" :rows="4" placeholder="请输入内容"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-collapse-item>
            </el-collapse>
        </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";
import { statusDic, materialDic } from "@/utils/basicDic";

const $emit = defineEmits(["success", "closed"]);
const visible = ref(false);
const isSaving = ref(false);

const activeNames = ref(["basic", "other"]);
const filterOptions = ref(XEUtils.clone(materialDic.unit, true));
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,
    materialType: null,
    needType: null,
    specification: null,
    unit: null,
    price: null,
    remark: null
});
const rules = reactive({
    tenantId: [{ required: true, message: "请选择所属租户" }],
    name: [{ required: true, message: "请输入物料名称" }],
    code: [{ required: true, message: "请输入物料编码" }],
    materialType: [{ required: true, message: "请选择物料类型" }],
    unit: [{ required: true, message: "请输入单位" }],
    price: [{ required: true, message: "请输入标准售价" }],
    needType: [{ required: true, message: "请选择物料来源" }]
});

const isSalable = computed(() => form.value.materialType && XEUtils.includes(materialDic.typeRelation["salable"], form.value.materialType));
const needTypeOptionDisabled = key => form.value.materialType && !XEUtils.includes(materialDic.typeRelation[key], form.value.materialType);
const materialOptionDisabled = key => form.value.needType && !XEUtils.includes(XEUtils.get(materialDic.typeRelation, form.value.needType, []), key);

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 filterMethod = query => {
    const fields = [];
    XEUtils.objectEach(materialDic.unit, (label, key) => (label.toLowerCase().includes(query.toLowerCase()) || key.toLowerCase().includes(query.toLowerCase())) && fields.push(key));
    filterOptions.value = XEUtils.pick(materialDic.unit, fields);
};

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

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

<style scoped>
.el-form {padding-left: 16px;padding-right: 22px;}
.el-form .el-input-number {width: 100%;}
.el-form .el-input-number :deep(.el-input__inner) {text-align: unset;}
.el-form .el-input-number :deep(.el-input__suffix) {font-size: 12px;}

.el-collapse {border: none;}
.el-collapse-item {margin-top: 15px;padding: 0 24px;background-color: var(--el-fill-color-blank);border: 1px solid var(--el-border-color-light);border-radius: 4px;color: var(--el-text-color-primary);box-shadow: var(--el-box-shadow-light);transition: var(--el-transition-duration);}
.el-collapse-item :deep(.el-collapse-item__header) {border-bottom-color: transparent;line-height: 55px;font-size: 16px;font-weight: bold;}
.el-collapse-item :deep(.el-collapse-item__header.is-active) {border-bottom: 1px solid var(--el-border-color-lighter);}
.el-collapse-item :deep(.el-collapse-item__wrap) {border: none;}
.el-collapse-item :deep(.el-collapse-item__content) {padding: 20px 28px 20px 0;}
</style>