import { computed, ref } from 'vue'; import { cloneDeep } from 'lodash'; const ACTIONS = { edit: '编辑', add: '新增', }; export default function ( { name, doCreate, doUpdate, refresh, initForm = {} }, formDialogRef ) { const saveInitForm = cloneDeep(initForm); const visible = ref(false); const type = ref(''); const title = computed(() => ACTIONS[type.value] + name); const loading = ref(false); let formRef = ref(null); const formData = ref({ ...initForm }); //新增 function handleAdd() { type.value = 'add'; visible.value = true; formData.value = cloneDeep(saveInitForm); } //编辑 function handleEdit(row) { type.value = 'edit'; visible.value = true; formData.value = { ...row }; } //保存 function handleSave() { if (!['edit', 'add'].includes(type.value)) { visible.value = false; return; } if (formDialogRef) { formRef = formDialogRef.value.formRef; } formRef?.validate().then(async (res) => { if (res !== true) return; const actions = { add: { api: () => doCreate(formData.value), cb: () => $message.success('新增成功'), }, edit: { api: () => doUpdate(formData.value), cb: () => $message.success('编辑成功'), }, }; const action = actions[type.value]; try { loading.value = true; const data = await action.api(); action.cb(); loading.value = visible.value = false; refresh(data); } catch (error) { loading.value = false; } }); } //删除 // function handleDelete(id, confirmOptions) { // if (!id) return; // $dialog.confirm({ // content: '确定删除?', // title: '提示', // async confirm() { // try { // loading.value = true; // const data = await doDelete(id); // $message.success('删除成功'); // loading.value = false; // refresh(data); // } catch (error) { // loading.value = false; // } // }, // ...confirmOptions, // }); // } return { visible, type, title, loading, handleAdd, // handleDelete, handleEdit, handleSave, formData, formRef, }; }