CustomRule.vue
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<script setup lang="ts">
  import { CustomRuleItemType } from './type';
  import { ComponentPublicInstance, nextTick, ref, unref, watch } from 'vue';
  import { BasicForm, FormActionType } from '/@/components/Form';
  import { getFormSchemas, RuleFormRecordItem } from './CustomRule.config';
  import { buildUUID } from '/@/utils/uuid';
  import { DefineComponentsBasicExpose } from '/#/utils';
  interface CustomRuleItemRefType {
    key: string;
    ref?: FormActionType;
    value?: CustomRuleItemType;
  }
  const props = withDefaults(
    defineProps<{
      value?: CustomRuleItemType[];
    }>(),
    {
      value: () => [],
    }
  );
  const customRuleListRef = ref<CustomRuleItemRefType[]>(
    Array.from({ length: 7 }, () => ({ key: buildUUID() }))
  );
  const setRuleItemRef = (
    el: Nullable<Element | ComponentPublicInstance>,
    ruleItem: CustomRuleItemRefType
  ) => {
    ruleItem.ref = el as unknown as FormActionType;
  };
  const validate = async () => {
    for (const item of unref(customRuleListRef)) {
      await item.ref?.validate?.();
    }
  };
  const getFieldsValue = (): CustomRuleItemType[] => {
    return unref(customRuleListRef).map((item) => {
      const { dayOfWeek, enabled, timeRange } = item.ref?.getFieldsValue() as RuleFormRecordItem;
      return {
        dayOfWeek,
        enabled,
        ...timeRange,
      };
    });
  };
  const setFieldsValue = async (ruleList: CustomRuleItemType[]) => {
    if (!ruleList.length) return;
    await nextTick();
    ruleList.forEach((value, index) => {
      const refEl = unref(customRuleListRef)[index];
      refEl.ref?.setFieldsValue({
        ...value,
        timeRange: {
          startsOn: value.startsOn,
          endsOn: value.endsOn,
        },
      } as RuleFormRecordItem);
    });
  };
  watch(
    () => props.value,
    () => {
      setFieldsValue(props.value);
    },
    { immediate: true }
  );
  defineExpose<DefineComponentsBasicExpose<CustomRuleItemType[]>>({
    getFieldsValue,
    setFieldsValue,
    validate,
  });
</script>
<template>
  <section>
    <template v-for="(item, index) in customRuleListRef" :key="index">
      <BasicForm
        :ref="(el) => setRuleItemRef(el, item)"
        :show-action-button-group="false"
        :schemas="getFormSchemas(index)"
        class="h-14"
      />
    </template>
  </section>
</template>