<script lang="ts" setup>
|
import type { FormInstance } from 'ant-design-vue';
|
|
import type { CSSProperties } from 'vue';
|
|
import { computed, inject, nextTick, onMounted, reactive, ref, toRefs, unref, watch } from 'vue';
|
|
import { useAttrs } from '@jnpf/hooks';
|
import { ModalClose } from '@jnpf/ui/modal';
|
|
import { $t } from '@vben/locales';
|
|
import { globalShareState } from '@vben-core/shared/global-state';
|
|
import { RedoOutlined } from '@ant-design/icons-vue';
|
import { Drawer as ADrawer, Modal as AModal, Form } from 'ant-design-vue';
|
import { pick } from 'lodash-es';
|
|
import ExtraRelationInfo from './ExtraRelationInfo.vue';
|
import { relationFormProps } from './props';
|
|
interface State {
|
extraData: any;
|
list: any[];
|
listQuery: any;
|
loading: boolean;
|
selectedRowKeys: any[];
|
selectedRows: any[];
|
total: number;
|
}
|
|
defineOptions({ inheritAttrs: false, name: 'JnpfRelationForm' });
|
const props = defineProps(relationFormProps);
|
const emit = defineEmits(['update:value', 'change']);
|
const attrs: any = useAttrs({ excludeDefaultKeys: false });
|
const formItemContext = Form.useInjectFormItemContext();
|
const { getConfigData, getDataChange, getFieldDataSelect } = globalShareState.getApi();
|
const { useGeneratorStore } = globalShareState.getStores();
|
const { RelationFormDetail } = globalShareState.getComponents();
|
const generatorStore = useGeneratorStore();
|
const emitter: any = inject('emitter');
|
const drawerPrefixCls = 'jnpf-basic-drawer';
|
const formPrefixCls = 'jnpf-basic-form';
|
const tablePrefixCls = 'jnpf-basic-table';
|
const drawerFooterPrefixCls = 'jnpf-basic-drawer-footer';
|
const detailRef = ref<any>(null);
|
const innerValue = ref<any[] | string | undefined>(undefined);
|
const selectRow = ref<any>(null);
|
const visible = ref(false);
|
const options = ref<any[]>([]);
|
const formElRef = ref<FormInstance>();
|
const tableElRef = ref<any>(null);
|
const indexColumn = {
|
align: 'center',
|
customRender: ({ index }) => index + 1,
|
dataIndex: 'index',
|
key: 'index',
|
title: $t('component.table.index'),
|
width: 50,
|
};
|
const state = reactive<State>({
|
extraData: {},
|
loading: false,
|
selectedRowKeys: [],
|
selectedRows: [],
|
total: 0,
|
list: [],
|
listQuery: {
|
currentPage: 1,
|
keyword: '',
|
pageSize: 20,
|
},
|
});
|
const { extraData, list, listQuery } = toRefs(state);
|
|
const getFormClass = computed(() => {
|
return [formPrefixCls, `${formPrefixCls}--compact`, 'search-form'];
|
});
|
const getDrawerFooterStyle = computed((): CSSProperties => {
|
const heightStr = `60px`;
|
return {
|
height: heightStr,
|
lineHeight: `calc(${heightStr} - 1px)`,
|
};
|
});
|
const getColumns = computed<any[]>(() => {
|
const columns = (props.columnOptions as any).map((o) => ({
|
dataIndex: o.value,
|
sorter: o.value.includes('jnpf_') ? false : { multiple: 1 },
|
ellipsis: true,
|
title: o.label,
|
}));
|
return [indexColumn, ...columns];
|
});
|
const searchInfo = computed(() => {
|
return {
|
columnOptions: (props.columnOptions as any).map((o) => o.value).join(','),
|
modelId: props.modelId,
|
relationField: props.relationField,
|
};
|
});
|
const getPagination = computed<any>(() => {
|
if (!props.hasPage) return false;
|
return {
|
current: state.listQuery.currentPage,
|
defaultPageSize: state.listQuery.pageSize,
|
pageSize: state.listQuery.pageSize,
|
pageSizeOptions: ['20', '50', '80', '100'],
|
showQuickJumper: true,
|
showSizeChanger: true,
|
showTotal: (total) => $t('component.table.total', { total }),
|
size: 'small',
|
total: state.total,
|
};
|
});
|
const getRowSelection = computed<any>(() => ({
|
onChange: setSelectedRowKeys,
|
selectedRowKeys: state.selectedRowKeys,
|
type: 'radio',
|
}));
|
const getScrollY = computed(() => {
|
let height = props.popupType === 'drawer' ? window.innerHeight - 120 - 52 - 38 : window.innerHeight * 0.7 - 52 - 38;
|
if (props.hasPage) height -= 44;
|
return height;
|
});
|
const getTableBindValues = computed(() => {
|
return {
|
class: unref(tablePrefixCls),
|
columns: unref(getColumns),
|
loading: state.loading,
|
pagination: unref(getPagination),
|
rowKey: unref(props).propsValue || 'id',
|
rowSelection: unref(getRowSelection),
|
customRow,
|
scroll: {
|
y: unref(getScrollY),
|
},
|
size: 'small',
|
};
|
});
|
const getSelectBindValue = computed(() => {
|
let className = unref(attrs).class ? `w-full ${unref(attrs).class}` : 'w-full';
|
if (props.disabled) className += ' disabled-select';
|
return {
|
...pick(props, ['size']),
|
allowClear: props.disabled ? false : props.allowClear,
|
class: className,
|
fieldNames: { label: unref(props).relationField, value: unref(props).propsValue || 'id' },
|
mode: props.multiple ? 'multiple' : '',
|
open: false,
|
placeholder: unref(props).placeholder,
|
showArrow: true,
|
showSearch: false,
|
style: Reflect.has(unref(attrs), 'style') ? unref(attrs).style : {},
|
};
|
});
|
|
watch(
|
() => unref(props.value),
|
(val) => {
|
setValue(val);
|
},
|
{ immediate: true },
|
);
|
|
function customRow(record: Recordable) {
|
return {
|
onClick: (e: Event) => {
|
e?.stopPropagation();
|
const tr: HTMLElement = (e as MouseEvent).composedPath?.().find((dom: any) => dom.tagName === 'TR') as HTMLElement;
|
if (!tr) return;
|
const isCheckbox = unref(getTableBindValues).rowSelection.type === 'checkbox';
|
const key = record[unref(getTableBindValues).rowKey];
|
if (isCheckbox) {
|
// 找到Checkbox,检查是否为disabled
|
const checkBox = tr.querySelector('input[type=checkbox]');
|
if (!checkBox || checkBox.hasAttribute('disabled')) return;
|
if (state.selectedRowKeys.includes(key)) {
|
const keyIndex = state.selectedRowKeys.indexOf(key);
|
state.selectedRowKeys.splice(keyIndex, 1);
|
state.selectedRows = state.selectedRows.filter((o) => o[unref(getTableBindValues).rowKey] !== key);
|
} else {
|
state.selectedRowKeys.push(key);
|
state.selectedRows.push(record);
|
}
|
} else {
|
// 找到radio,检查是否为disabled
|
const radio = tr.querySelector('input[type=radio]');
|
if (!radio || radio.hasAttribute('disabled')) return;
|
state.selectedRowKeys = [key];
|
state.selectedRows = [record];
|
}
|
},
|
};
|
}
|
function setValue(value) {
|
const relationData = generatorStore.getRelationData;
|
if ((props.multiple && (props.value as any[]).length === 0) || (!props.multiple && !props.value && props.value !== 0)) {
|
setNullValue();
|
return;
|
}
|
if (!props.modelId) return;
|
if (!props.multiple) {
|
const query: any = { id: value };
|
if (props.propsValue) query.propsValue = props.propsValue;
|
getDataChange(props.modelId, query).then((res) => {
|
if ((props.multiple && (props.value as any[]).length === 0) || (!props.multiple && !props.value && props.value !== 0)) {
|
setNullValue();
|
return;
|
}
|
if (!res.data || !res.data.data) return;
|
const data = JSON.parse(res.data.data);
|
state.extraData = data;
|
innerValue.value = value;
|
options.value = [{ ...data, id: res.data.id }];
|
if (!props.field) return;
|
relationData[props.field] = { ...data, id: res.data.id };
|
generatorStore.setRelationData(relationData);
|
emitter.emit('setRelationData', { jnpfRelationField: props.field, ...data, id: res.data.id });
|
});
|
}
|
}
|
function setNullValue() {
|
const relationData = generatorStore.getRelationData;
|
innerValue.value = props.multiple ? [] : undefined;
|
state.extraData = {};
|
options.value = [];
|
selectRow.value = null;
|
if (!props.field) return;
|
relationData[props.field] = {};
|
generatorStore.setRelationData(relationData);
|
emitter.emit('setRelationData', { jnpfRelationField: props.field });
|
}
|
function onChange() {
|
options.value = [];
|
emit('update:value', '');
|
emit('change', '', {});
|
formItemContext.onFieldChange();
|
}
|
function getForm() {
|
const form = unref(formElRef);
|
if (!form) {
|
throw new Error('form is null!');
|
}
|
return form;
|
}
|
async function openSelectModal() {
|
if (props.disabled) {
|
if (!props.value) return;
|
getConfigData(props.modelId).then((res) => {
|
if (!res.data || !res.data.formData) return;
|
const formConf = JSON.parse(res.data.formData);
|
formConf.popupType = 'general';
|
const data = { formConf, id: props.value, modelId: props.modelId, propsValue: props.propsValue };
|
detailRef.value?.init(data);
|
});
|
return;
|
}
|
visible.value = true;
|
nextTick(() => {
|
handleReset();
|
state.selectedRowKeys = innerValue.value ? [innerValue.value] : [];
|
const tableEl = tableElRef.value?.$el;
|
const bodyEl = tableEl.querySelector('.ant-table-body');
|
bodyEl!.style.height = `${unref(getScrollY)}px`;
|
});
|
}
|
function handleCancel() {
|
visible.value = false;
|
}
|
function handleSubmit() {
|
if (state.selectedRowKeys.length === 0 && state.selectedRows.length === 0) return;
|
if (state.selectedRows.length === 0) {
|
emit('update:value', innerValue.value);
|
emit('change', innerValue.value, options.value[0]);
|
formItemContext.onFieldChange();
|
handleCancel();
|
return;
|
}
|
selectRow.value = state.selectedRows[0];
|
options.value = state.selectedRows;
|
innerValue.value = unref(selectRow)[props.propsValue || 'id'];
|
emit('update:value', unref(selectRow)[props.propsValue || 'id']);
|
emit('change', unref(selectRow)[props.propsValue || 'id'], unref(selectRow));
|
formItemContext.onFieldChange();
|
handleCancel();
|
}
|
function handleSearch() {
|
state.listQuery.currentPage = 1;
|
state.listQuery.pageSize = props.hasPage ? props.pageSize : 100000;
|
initData();
|
}
|
function handleReset() {
|
getForm().resetFields();
|
state.listQuery.keyword = '';
|
handleSearch();
|
}
|
function initData() {
|
if (!props.modelId || !props.relationField) return;
|
state.loading = true;
|
const query = {
|
...state.listQuery,
|
...unref(searchInfo),
|
propsValue: props.propsValue,
|
queryType: props.queryType,
|
};
|
getFieldDataSelect(query)
|
.then((res) => {
|
state.list = res.data.list;
|
state.total = res.data.pagination.total;
|
state.loading = false;
|
})
|
.catch(() => {
|
state.loading = false;
|
});
|
}
|
function handleTableChange(pagination, _f, sorter, type) {
|
if (type?.action === 'sort' && sorter) {
|
if (Array.isArray(sorter)) {
|
const sortList = sorter.map((o) => (o.order === 'descend' ? '-' : '') + o.field);
|
state.listQuery.sidx = sortList.join(',');
|
} else {
|
const { field, order } = sorter;
|
state.listQuery.sidx = field && order ? (order === 'descend' ? '-' : '') + field : undefined;
|
}
|
}
|
if (type?.action === 'paginate') {
|
state.listQuery.currentPage = pagination.current;
|
state.listQuery.pageSize = pagination.pageSize;
|
}
|
initData();
|
}
|
function setSelectedRowKeys(selectedRowKeys, selectedRows) {
|
state.selectedRowKeys = selectedRowKeys;
|
state.selectedRows = selectedRows;
|
}
|
|
onMounted(() => {
|
state.listQuery.pageSize = props.hasPage ? props.pageSize : 100000;
|
});
|
</script>
|
|
<template>
|
<div class="common-container">
|
<a-select v-model:value="innerValue" v-bind="getSelectBindValue" :options="options" @change="onChange" @click="openSelectModal" />
|
<template v-if="popupType === 'dialog'">
|
<AModal
|
v-model:open="visible"
|
:mask-closable="false"
|
:title="popupTitle"
|
:width="popupWidth"
|
class="common-container-modal"
|
@cancel="handleCancel"
|
@ok="handleSubmit">
|
<template #closeIcon>
|
<ModalClose :can-fullscreen="false" @cancel="handleCancel" />
|
</template>
|
<div class="jnpf-common-search-box jnpf-common-search-box-modal">
|
<a-form ref="formElRef" :class="getFormClass" :colon="false" :model="listQuery" label-align="right">
|
<a-row :gutter="10">
|
<a-col :span="8">
|
<a-form-item :label="$t('common.keyword')" name="keyword">
|
<a-input v-model:value="listQuery.keyword" :placeholder="$t('common.enterKeyword')" allow-clear @press-enter="handleSearch" />
|
</a-form-item>
|
</a-col>
|
<a-col :span="8">
|
<a-form-item label=" ">
|
<a-button class="mr-2" type="primary" @click="handleSearch">{{ $t('common.queryText') }}</a-button>
|
<a-button @click="handleReset">{{ $t('common.resetText') }}</a-button>
|
</a-form-item>
|
</a-col>
|
</a-row>
|
</a-form>
|
<div class="jnpf-common-search-box-right">
|
<a-tooltip placement="top">
|
<template #title>
|
<span>{{ $t('common.redo') }}</span>
|
</template>
|
<RedoOutlined class="jnpf-common-search-box-right-icon" @click="initData" />
|
</a-tooltip>
|
</div>
|
</div>
|
<a-table :data-source="list" v-bind="getTableBindValues" ref="tableElRef" @change="handleTableChange">
|
<template #bodyCell="{ column, record }">
|
<template v-if="column.dataIndex !== 'index'">{{ record[column.dataIndex] }}</template>
|
</template>
|
</a-table>
|
</AModal>
|
</template>
|
<template v-if="popupType === 'drawer'">
|
<ADrawer v-model:open="visible" :class="`${drawerPrefixCls} common-container-drawer`" :title="popupTitle" :width="popupWidth">
|
<div class="common-container-drawer-body">
|
<div class="jnpf-common-search-box jnpf-common-search-box-modal">
|
<a-form ref="formElRef" :class="getFormClass" :colon="false" :model="listQuery" label-align="right">
|
<a-row :gutter="10">
|
<a-col :span="8">
|
<a-form-item :label="$t('common.keyword')" name="keyword">
|
<a-input v-model:value="listQuery.keyword" :placeholder="$t('common.enterKeyword')" allow-clear @press-enter="handleSearch" />
|
</a-form-item>
|
</a-col>
|
<a-col :span="8">
|
<a-form-item label=" ">
|
<a-button class="mr-2" type="primary" @click="handleSearch">{{ $t('common.queryText') }}</a-button>
|
<a-button @click="handleReset">{{ $t('common.resetText') }}</a-button>
|
</a-form-item>
|
</a-col>
|
</a-row>
|
</a-form>
|
<div class="jnpf-common-search-box-right">
|
<a-tooltip placement="top">
|
<template #title>
|
<span>{{ $t('common.redo') }}</span>
|
</template>
|
<RedoOutlined class="jnpf-common-search-box-right-icon" @click="initData" />
|
</a-tooltip>
|
</div>
|
</div>
|
<a-table :data-source="list" v-bind="getTableBindValues" ref="tableElRef" @change="handleTableChange">
|
<template #bodyCell="{ column, record }">
|
<template v-if="column.dataIndex !== 'index'">{{ record[column.dataIndex] }}</template>
|
</template>
|
</a-table>
|
</div>
|
<div :class="drawerFooterPrefixCls" :style="getDrawerFooterStyle">
|
<a-button class="mr-[10px]" @click="handleCancel">{{ $t('common.cancelText') }}</a-button>
|
<a-button class="mr-[10px]" type="primary" @click="handleSubmit">{{ $t('common.okText') }}</a-button>
|
</div>
|
</ADrawer>
|
</template>
|
<component :is="RelationFormDetail" ref="detailRef" v-if="RelationFormDetail" />
|
<ExtraRelationInfo v-if="extraOptions.length > 0 && JSON.stringify(extraData) !== '{}'" :data="extraData" :extra-options="extraOptions" />
|
</div>
|
</template>
|