pms-aomei/src/components/DialogWithMenu.vue

473 lines
16 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<el-dialog
class="dialog-with-menu"
:visible="dialogVisible"
:destroy-on-close="false"
@close="handleClose"
:close-on-click-modal="configs.clickModalToClose ?? true"
>
<!-- title -->
<div slot="title" class="dialog-title">
<h1 class="">
{{ detailMode ? "查看详情" : dataForm.id ? "编辑" : "新增" }}
</h1>
</div>
<div class="dialog-body__inner relative">
<el-button
v-if="dataForm.id && !detailMode && /属性/.test(activeMenu)"
plain
type="primary"
size="small"
class="at-right-top"
style="margin-bottom: 16px"
@click="handleAddParam()"
>+ 添加</el-button
>
<!-- menu -->
<el-tabs v-model="activeMenu" type="card" @tab-click="handleTabClick">
<!-- <el-tab-pane v-for="(tab, index) in configs.menu" :key="index" :label="tab.name" :name="tab.name"> -->
<el-tab-pane v-for="(tab, index) in actualMenus" :key="index" :label="tab.name" :name="tab.name">
<div v-if="index === 0">
<!-- form -->
<el-form ref="dataForm" :model="dataForm" v-loading="loadingStatus">
<el-row v-for="(row, rowIndex) in configs.form.rows" :key="'row_' + rowIndex" :gutter="20">
<el-col v-for="(col, colIndex) in row" :key="colIndex" :span="24 / row.length">
<el-form-item :label="col.label" :prop="col.prop" :rules="col.rules || null">
<el-input v-if="col.input" v-model="dataForm[col.prop]" clearable :disabled="detailMode" v-bind="col.elparams" />
<el-select
v-if="col.select"
v-model="dataForm[col.prop]"
clearable
:disabled="detailMode"
v-bind="col.elparams"
@change="handleSelectChange(col, $event)"
>
<el-option v-for="(opt, optIdx) in col.options" :key="'option_' + optIdx" :label="opt.label" :value="opt.value" />
</el-select>
<el-switch
v-if="col.switch"
v-model="dataForm[col.prop]"
:active-value="1"
:inactive-value="0"
@change="handleSwitchChange"
:disabled="detailMode"
/>
<el-input v-if="col.textarea" type="textarea" v-model="dataForm[col.prop]" :disabled="detailMode" v-bind="col.elparams" />
<!-- add more... -->
</el-form-item>
</el-col>
</el-row>
</el-form>
</div>
<div v-if="dataForm.id && index === 1">
<BaseListTable :table-config="null" :column-config="filteredTableProps" :table-data="subList" @operate-event="handleTableRowOperate" />
<!-- paginator -->
</div>
</el-tab-pane>
</el-tabs>
</div>
<!-- sub dialog -->
<small-dialog
:append-to-body="true"
v-if="showSubDialog"
ref="subDialog"
:url="urls.subase"
:configs="configs.subDialog"
:related-id="dataForm.id"
@refreshDataList="getSubList"
></small-dialog>
<!-- footer -->
<div slot="footer">
<template v-for="(operate, index) in configs.form.operations">
<el-button v-if="showButton(operate)" :key="'operation_' + index" :type="operate.type" @click="handleBtnClick(operate)">{{
operate.label
}}</el-button>
</template>
<el-button @click="handleBtnClick({ name: 'cancel' })">取消</el-button>
</div>
</el-dialog>
</template>
<script>
import { pick as __pick } from "@/utils/filters";
import SmallDialog from "@/components/SmallDialog.vue";
import BaseListTable from "@/components/BaseListTable.vue";
export default {
name: "DialogWithMenu",
components: { SmallDialog, BaseListTable },
props: {
configs: {
type: Object,
default: () => ({}),
},
dialogVisible: {
type: Boolean,
default: false,
},
},
inject: ["urls"],
data() {
const dataForm = {};
this.configs.form.rows.forEach((row) => {
row.forEach((col) => {
if (col.upload) dataForm[col.prop] = col.default ?? [];
else dataForm[col.prop] = col.default ?? null;
if (col.fetchData)
col.fetchData().then(({ data: res }) => {
console.log("[Fetch Data]", res.data.list);
if (res.code === 0 && res.data.list) {
this.$set(
col,
"options",
res.data.list.map((i) => ({ label: i.name, value: i.id }))
);
// col.options = res.data.list;
} else {
col.options.splice(0);
}
// dataForm[col.prop] = col.default ?? null; // not perfect!
});
else if (col.fetchTreeData) {
// 获取设备类型时触发的用于前端构建属性结构约定parentId 为0时是顶级节点
col.fetchTreeData().then(({ data: res }) => {
console.log("[Fetch Tree Data]", res.data.list);
if (res.code === 0 && res.data.list) {
// 先把数据先重构成一个对象
const obj = {};
res.data.list.map((item) => {
obj[item.id] = item;
});
// 再过滤这个对象
let filteredList = reConstructTreeData(obj);
console.log("** filteredList **", filteredList);
// 最后设置 options
this.$set(col, "options", filteredList);
} else {
col.options.splice(0);
}
});
}
});
});
return {
// configs,
loadingStatus: false,
activeMenu: this.configs.menu[0].name,
dataForm,
detailMode: false,
showBaseDialog: false,
baseDialogConfig: null,
subList: [],
showSubDialog: false,
};
},
computed: {
actualMenus() {
return this.configs.menu.filter((m) => {
if (m.onlyEditMode && !this.dataForm.id) {
return false;
}
return true;
});
},
filteredTableProps() {
return this.detailMode ? this.configs.table.props.filter((v) => v.prop !== "operations") : this.configs.table.props;
},
},
methods: {
k() {
console.log("[DialogWithMenu] closed");
},
/** utitilities */
showButton(operate) {
const notDetailMode = !this.detailMode;
const showAlways = operate.showAlways ?? false;
const editMode = operate.showOnEdit && this.dataForm.id;
const addMode = !operate.showOnEdit && !this.dataForm.id;
const permission = operate.permission ? this.$hasPermission(operate.permission) : true;
return notDetailMode && (showAlways || ((editMode || addMode) && permission));
},
resetForm(excludeId = false, immediate = false) {
setTimeout(
() => {
Object.keys(this.dataForm).forEach((key) => {
if (excludeId && key === "id") return;
this.dataForm[key] = null;
});
this.activeMenu = this.configs.menu[0].name;
this.$refs.dataForm[0].clearValidate();
},
immediate ? 0 : 200
);
},
/** init **/
init(id, detailMode) {
// this.dialogVisible = true;
if (this.$refs.dataForm && this.$refs.dataForm.length) {
// 当不是首次渲染dialog的时候一开始就清空验证信息本组件的循环里只有一个 dataForm 所以只用取 [0] 即可
this.$refs.dataForm[0].clearValidate();
}
console.log("[dialog] DialogWithHead init():", id, detailMode);
this.detailMode = detailMode ?? false;
this.$nextTick(() => {
// this.$refs['dataForm'].resetFields();
this.dataForm.id = id || null;
if (this.dataForm.id) {
// 如果是编辑
this.loadingStatus = true;
// 提前获取属性列表
this.getSubList();
// 获取详情
this.$http.get(this.urls.base + `/${this.dataForm.id}`).then(({ data: res }) => {
if (res && res.code === 0) {
const dataFormKeys = Object.keys(this.dataForm);
console.log("keys ===> ", dataFormKeys);
// console.log('data form keys: ', dataFormKeys, pick(res.data, dataFormKeys))
this.dataForm = __pick(res.data, dataFormKeys);
console.log("pick(res.data, dataFormKeys) ===> ", __pick(res.data, dataFormKeys));
// LABEL: FILE_RELATED
/** 对文件下载进行分流 */
// this.fileList = {};
// if (this.dataForm.files) {
// // console.log('files: ', this.dataForm.files)
// this.dataForm.files.forEach((file) => {
// // const fileName = file.fileurls.split('/').pop()
// /** [1] 处理 fileList */
// // if (Object.hasOwn(this.fileList, file.typeCode)) {
// if (this.fileList.hasOwnProperty(file.typeCode)) {
// /** 已存在 */
// // this.fileList[file.typeCode].push({ id: file.id, name: fileName, typeCode: file.typeCode })
// this.fileList[file.typeCode].push(file);
// } else {
// // this.fileList[file.typeCode] = [{ id: file.id, name: fileName, typeCode: file.typeCode }]
// this.fileList[file.typeCode] = [file];
// }
// /** [2] 处理 fileForm */
// // if (Object.hasOwn(this.fileForm, file.typeCode)) {
// if (this.fileForm.hasOwnProperty(file.typeCode)) {
// this.fileForm[file.typeCode].push(file.id);
// } else {
// this.fileForm[file.typeCode] = [file.id];
// }
// });
// }
}
this.loadingStatus = false;
});
} else {
// 如果不是编辑
// this.dialogVisible = true;
}
});
},
/** handlers */
handleSelectChange(col, eventValue) {
console.log("[dialog] select change: ", col, eventValue);
},
handleSwitchChange(val) {
console.log("[dialog] switch change: ", val, this.dataForm);
},
handleBtnClick(payload) {
console.log("btn click payload: ", payload);
if ("name" in payload) {
switch (payload.name) {
case "cancel":
this.handleClose();
break;
case "reset":
this.resetForm(true, true); // true means exclude id
break;
case "add":
case "update": {
this.$refs.dataForm[0].validate((passed, result) => {
if (passed) {
// 如果通过验证
this.loadingStatus = true;
const method = payload.name === "add" ? "POST" : "PUT";
this.$http({
url: this.urls.base,
method,
data: this.dataForm,
})
.then(({ data: res }) => {
console.log("[add&update] res is: ", res);
this.$message.success(payload.name === "add" ? "添加成功" : "更新成功");
this.$emit("refreshDataList");
this.loadingStatus = false;
this.handleClose();
})
.catch((errMsg) => {
this.$message.error("参数错误:" + errMsg);
if (this.loadingStatus) this.loadingStatus = false;
});
} else {
// 没有通过验证
// this.$message.error(JSON.stringify(result));
this.$message.error("请核查字段信息");
}
});
}
}
} else {
console.log("[x] 不是这么用的! 缺少name属性");
}
},
handleTabClick(payload) {
// console.log("tab click payload: ", this.activeMenu);
// if (this.activeMenu === this.configs.menu[1].name) {
// // 获取数据
// this.getSubList();
// }
},
getSubList(page = 1, size = 20) {
const params = {};
params.page = page;
params.limit = size;
const requiredParams = this.configs.table.extraParams;
if (requiredParams) {
if (Array.isArray(requiredParams)) {
requiredParams.forEach((str) => {
if (/id/i.test(str)) {
params[str] = this.dataForm.id;
} else {
params[str] = "";
}
});
} else if (typeof requiredParams === "string") {
// 如果需要额外参数,一般肯定需要
params[this.configs.table.extraParams] = this.dataForm.id;
// 此时 dataForm.id 一定是存在的
}
}
this.$http.get(this.urls.subpage, { params }).then(({ data: res }) => {
console.log("[subList] getSubList:", res);
if (res.code === 0 && res.data?.list) {
// 有数据
this.subList = res.data.list;
} else {
this.subList.splice(0);
}
});
},
handleAddParam(id) {
this.showSubDialog = true;
this.$nextTick(() => {
this.$refs.subDialog.init(id ?? null);
});
},
handleClose() {
this.resetForm();
this.$emit("update:dialogVisible", false);
},
/** 列表handlers */
handleAddItem() {
// console.log('[dialog] handleAddItem ot list...');
this.showBaseDialog = true;
this.$nextTick(() => {
console.log("[sub-dialog] ", this.$refs["sub-dialog"].init());
});
},
handleTableRowOperate({ type, data }) {
console.log("handleTableRowOperate", type, data);
switch (type) {
case "delete": {
// 确认是否删除
return this.$confirm(`是否删除条目: ${data}`, "提示", {
confirmButtonText: "确认",
cancelButtonText: "我再想想",
type: "warning",
})
.then(() => {
// this.$http.delete(this.urls.base + `/${data}`).then((res) => {
this.$http({
url: this.urls.subase,
method: "DELETE",
data: [`${data}`],
}).then(({ data: res }) => {
if (res.code === 0) {
this.$message.success({
message: "删除成功!",
duration: 1000,
onClose: () => {
this.getSubList(1, 20);
},
});
}
});
})
.catch((err) => {});
}
case "edit": {
this.handleAddParam(data); /** data is ==> id */
break;
}
// case 'view-detail-action':
// this.openDialog(data, true);
// break;
}
},
},
};
</script>
<style scoped>
.el-menu {
margin: 16px 0 !important;
}
.el-menu.el-menu--horizontal {
border: none !important;
/* background: #0f02 !important; */
}
/* .el-menu--horizontal > .el-menu-item.is-active { */
/* border-bottom-color: #0b58ff; */
/* } */
.dialog-with-menu >>> .el-dialog__body {
/* padding-top: 16px !important;
padding-bottom: 16px !important; */
padding-top: 0 !important;
padding-bottom: 0 !important;
}
.el-select {
width: 100% !important;
}
.dialog-with-menu >>> .el-dialog__header {
padding: 10px 20px 10px;
/* background: linear-gradient(to bottom, rgba(0, 0, 0, 0.25), white); */
}
.relative {
position: relative;
}
.at-right-top {
position: absolute;
top: 0;
right: 0;
z-index: 10000;
}
</style>