import dayjs from 'dayjs';
import { nextTick } from 'vue';
import { useDictStore } from '/@/store/modules/dict';
import { useI18n } from '/@/hooks/web/useI18n';
const dictStore = useDictStore();
const { t } = useI18n();
export type Dimension = 'year' | 'month' | 'date' | 'time';
export const defaultValueMap = {
year: dayjs(),
month: dayjs(),
date: dayjs(),
time: dayjs(),
};
export const defaultFormatMap = {
year: 'YYYY',
month: 'YYYY-MM',
date: 'YYYY-MM-DD',
time: 'YYYY-MM-DD HH',
};
export const disableMap = {
year: {
type: 'year',
value: 2,
},
month: {
type: 'month',
value: 11,
},
date: {
type: 'days',
value: 30,
},
time: {
type: 'days',
value: 1,
},
};
/**
* @description: 维度操作方法
* @param {Dimension} defaultVal 默认维度
* @param {string} field rangePicker 字段ID
* @param {any} formActionType 表单操作
* @return {*}
*/
export const dimensionAction = (defaultVal: Dimension, field: string, formActionType: any) => {
const { updateSchema, setFieldsValue } = formActionType;
let hackValue: any = undefined;
let disable: any = disableMap[defaultVal];
let dateTemp: any = defaultValueMap[defaultVal];
let format: any = defaultFormatMap[defaultVal];
const disabledDate = (current) => {
if (!dateTemp || dateTemp.length === 0 || disable.type === 'year') {
// 年份不做限制,数据量过大,会导致弹框卡顿
return false;
}
const tooLate = current && current.diff(dateTemp[0], disable.type) > disable.value;
const tooEarly = dateTemp[1] && dateTemp[1].diff(current, disable.type) > disable.value;
return tooEarly || tooLate;
};
const calendarChange = (date) => {
dateTemp = date;
};
const openChange = (open: boolean) => {
if (open) {
hackValue = [];
dateTemp = [];
} else {
hackValue = undefined;
}
setFieldsValue({
[field]: hackValue || dateTemp,
});
};
nextTick(() => {
setFieldsValue({
[field]: hackValue || dateTemp,
});
});
return {
options: dictStore.getTimeRange.map((item) => ({
label: t(`common.${item}`),
value: item,
})),
placeholder: `${t('common.chooseText')}${t('energy-balance.queryTime')}`,
useSearch: true,
onChange: (queryType) => {
disable = disableMap[queryType];
dateTemp = defaultValueMap[queryType];
format = defaultFormatMap[queryType];
setFieldsValue({
timeRange: hackValue || dateTemp,
});
updateSchema({
field,
componentProps: {
format: format,
showTime: queryType === 'time',
picker: queryType === 'time' ? 'date' : queryType,
disabledDate: disabledDate,
onCalendarChange: calendarChange,
onOpenChange: openChange,
},
});
},
};
};
/**
* @description: 重置维度和时间范围
* @return {*}
*/
export const resetPicker = (
defaultVal: Dimension,
dimensionField: string,
timeRangeField: string,
formActionType: any,
) => {
const { updateSchema, setFieldsValue } = formActionType;
updateSchema({
field: timeRangeField,
componentProps: {
format: defaultFormatMap[defaultVal],
showTime: defaultVal === 'time',
picker: defaultVal === 'time' ? 'date' : defaultVal,
},
});
setFieldsValue({
[dimensionField]: defaultVal,
[timeRangeField]: defaultValueMap[defaultVal],
});
};