import {computed, reactive, watch} from "@peryl/react-compose"; import {deepcopy} from "@peryl/utils/deepcopy"; import {iPlcGroupPropsType, iPlcPropsType, tPlcType} from "../utils/plc.utils"; /** * 获取可以修改的plc props state * @author 韦胜健 * @date 2022.10.29 19:10 */ export function usePlcPropsState>(propsRef: { value: Props }): { state: Props, propsState: Props } { /** * 初始化可以修改的state * @author 韦胜健 * @date 2022.10.29 19:10 */ const state = reactive(Object.keys(propsRef.value).reduce((prev, propKey) => { prev[propKey] = undefined; return prev; }, {} as any)); /** * 代理以及监听props变化 * @author 韦胜健 * @date 2022.10.29 19:11 */ const propsState = reactive(Object.keys(propsRef.value).reduce((prev, propKey) => { /*当props对应的属性值变化时,清理掉内部临时修改的值,以props变化的值为准*/ watch(() => propsRef.value[propKey], () => {(propsState as any)[propKey] = undefined;}) ;(prev as any)[propKey] = computed({ get() { if (state[propKey] !== undefined) {return state[propKey];} return propsRef.value[propKey]; }, set(val: any) { if (state[propKey] !== val) { state[propKey] = val; } }, }); return prev; }, {} as Props)); return { state, propsState: propsState as any, }; } /** * 缓存的plc状态 * @author 韦胜健 * @date 2022.10.29 19:11 */ export type tPlcCacheState = { state: iPlcGroupPropsType | iPlcPropsType, children?: tPlcCacheStateData, key: string, } /** * plc缓存类型 * @author 韦胜健 * @date 2022.10.29 19:11 */ export type tPlcCacheStateData = Record /** * 根据plc的信息计算一个唯一的标识 * @author 韦胜健 * @date 2022.10.29 19:11 */ export function getPlcKey(i: tPlcType) {return i.group ? ('G' + i.props.title || 'GT') : `${i.props.title || 'PT'}:${i.props.field || 'PF'}`;} /** * 获取多级表头的state(只要state) * @author 韦胜健 * @date 2021/6/2 14:58 */ export function getPlcPropsState(sourceList: tPlcType[]): tPlcCacheStateData { const stateList = [] as tPlcCacheState[]; sourceList.forEach(i => { stateList.push({ state: deepcopy(i.getState()), children: !i.group ? undefined : getPlcPropsState(i.children), key: getPlcKey(i), }); }); return stateList.reduce((prev, item) => { prev[item.key] = item; return prev; }, {} as Record); } /** * 应用多级表头的state * @author 韦胜健 * @date 2021/6/2 15:04 */ export function applyPlcPropsState(stateData: tPlcCacheStateData, plcList: tPlcType[]) { plcList.forEach(plcType => { const key = getPlcKey(plcType); if (!!stateData[key]) { Object.assign(plcType.getState(), stateData[key].state); if (plcType.group && !!stateData[key].children) { applyPlcPropsState(stateData[key].children!, plcType.children); } } }); }