陈文彬
2020-10-01 2f268ca8f43d98687ffd809e2c1d140d29033bd6
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { defineComponent, computed, unref, toRef } from 'vue';
import { Form, Col } from 'ant-design-vue';
import { componentMap } from './componentMap';
 
import type { PropType } from 'vue';
import type { FormProps } from './types/form';
import type { FormSchema } from './types/form';
import { isBoolean, isFunction } from '/@/utils/is';
import { useItemLabelWidth } from './hooks/useLabelWidth';
import { getSlot } from '/@/utils/helper/tsxHelper';
import { BasicHelp } from '/@/components/Basic';
import { createPlaceholderMessage } from './helper';
import { upperFirst, cloneDeep } from 'lodash-es';
import { ValidationRule } from 'ant-design-vue/types/form/form';
export default defineComponent({
  name: 'BasicFormItem',
  inheritAttrs: false,
  props: {
    schema: {
      type: Object as PropType<FormSchema>,
      default: () => {},
    },
    formProps: {
      type: Object as PropType<FormProps>,
      default: {},
    },
    allDefaultValues: {
      type: Object as PropType<any>,
      default: {},
    },
    formModel: {
      type: Object as PropType<any>,
      default: {},
    },
  },
  setup(props, { slots }) {
    const itemLabelWidthRef = useItemLabelWidth(toRef(props, 'schema'), toRef(props, 'formProps'));
 
    const getValuesRef = computed(() => {
      const { allDefaultValues, formModel, schema } = props;
      const { mergeDynamicData } = props.formProps;
      return {
        field: schema.field,
        model: formModel,
        values: {
          ...mergeDynamicData,
          ...allDefaultValues,
          ...formModel,
        },
        schema: schema,
      };
    });
    const getShowRef = computed(() => {
      const { show, ifShow, isAdvanced } = props.schema;
      const { showAdvancedButton } = props.formProps;
      const itemIsAdvanced = showAdvancedButton ? !!isAdvanced : true;
      let isShow = true;
      let isIfShow = true;
 
      if (isBoolean(show)) {
        isShow = show;
      }
      if (isBoolean(ifShow)) {
        isIfShow = ifShow;
      }
      if (isFunction(show)) {
        isShow = show(unref(getValuesRef));
      }
      if (isFunction(ifShow)) {
        isIfShow = ifShow(unref(getValuesRef));
      }
      isShow = isShow && itemIsAdvanced;
      return { isShow, isIfShow };
    });
 
    const getDisableRef = computed(() => {
      const { disabled: globDisabled } = props.formProps;
      const { dynamicDisabled } = props.schema;
      let disabled = !!globDisabled;
      if (isBoolean(dynamicDisabled)) {
        disabled = dynamicDisabled;
      }
 
      if (isFunction(dynamicDisabled)) {
        disabled = dynamicDisabled(unref(getValuesRef));
      }
 
      return disabled;
    });
 
    function handleRules(): ValidationRule[] {
      const {
        rules: defRules = [],
        component,
        rulesMessageJoinLabel,
        label,
        dynamicRules,
      } = props.schema;
 
      if (isFunction(dynamicRules)) {
        return dynamicRules(unref(getValuesRef));
      }
 
      const rules: ValidationRule[] = cloneDeep(defRules);
      const requiredRuleIndex: number = rules.findIndex(
        (rule) => Reflect.has(rule, 'required') && !Reflect.has(rule, 'validator')
      );
      const { rulesMessageJoinLabel: globalRulesMessageJoinLabel } = props.formProps;
      if (requiredRuleIndex !== -1) {
        const rule = rules[requiredRuleIndex];
        if (rule.required && component) {
          const joinLabel = Reflect.has(props.schema, 'rulesMessageJoinLabel')
            ? rulesMessageJoinLabel
            : globalRulesMessageJoinLabel;
          rule.message =
            rule.message || createPlaceholderMessage(component) + `${joinLabel ? label : ''}`;
          if (component.includes('Input') || component.includes('Textarea')) {
            rule.whitespace = true;
          }
          if (
            component.includes('DatePicker') ||
            component.includes('MonthPicker') ||
            component.includes('WeekPicker') ||
            component.includes('TimePicker')
          ) {
            rule.type = 'object';
          }
          if (component.includes('RangePicker')) {
            rule.type = 'array';
          }
        }
      }
 
      // 最大输入长度规则校验
      const characterInx = rules.findIndex((val) => val.max);
      if (characterInx !== -1 && !rules[characterInx].validator) {
        rules[characterInx].message =
          rules[characterInx].message || `字符数应小于${rules[characterInx].max}位`;
      }
      return rules;
    }
    function renderComponent() {
      const {
        componentProps,
        renderComponentContent,
        component,
        field,
        changeEvent = 'change',
      } = props.schema;
 
      const isCheck = component && ['Switch'].includes(component);
 
      const eventKey = `on${upperFirst(changeEvent)}`;
      const on = {
        [eventKey]: (e: any) => {
          if (propsData[eventKey]) {
            propsData[eventKey](e);
          }
          if (e && e.target) {
            (props.formModel as any)[field] = e.target.value;
          } else {
            (props.formModel as any)[field] = e;
          }
        },
      };
 
      const Comp = componentMap.get(component);
 
      const { autoSetPlaceHolder, size } = props.formProps;
      const propsData: any = {
        allowClear: true,
        getPopupContainer: (trigger: Element) => trigger.parentNode,
        size,
        ...componentProps,
        disabled: unref(getDisableRef),
      };
 
      const isCreatePlaceholder = !propsData.disabled && autoSetPlaceHolder;
      let placeholder;
      // RangePicker place为数组
      if (isCreatePlaceholder && component !== 'RangePicker' && component) {
        placeholder =
          (componentProps && componentProps.placeholder) || createPlaceholderMessage(component);
      }
      propsData.placeholder = placeholder;
      propsData.codeField = field;
      propsData.formValues = unref(getValuesRef);
 
      const bindValue = {
        [isCheck ? 'checked' : 'value']: (props.formModel as any)[field],
      };
      if (!renderComponentContent) {
        return <Comp {...propsData} {...on} {...bindValue} />;
      }
      return (
        <Comp {...propsData} {...on} {...bindValue}>
          {{
            ...renderComponentContent(unref(getValuesRef)),
          }}
        </Comp>
      );
    }
 
    function renderLabelHelpMessage() {
      const { label, helpMessage, helpComponentProps } = props.schema;
      if (!helpMessage || (Array.isArray(helpMessage) && helpMessage.length === 0)) {
        return label;
      }
      return (
        <span>
          {label}
          <BasicHelp class="mx-1" text={helpMessage} {...helpComponentProps} />
        </span>
      );
    }
    function renderItem() {
      const { itemProps, slot, render, field } = props.schema;
      const { labelCol, wrapperCol } = unref(itemLabelWidthRef);
      const { colon } = props.formProps;
      const getContent = () => {
        return slot
          ? getSlot(slots, slot)
          : render
          ? render(unref(getValuesRef))
          : renderComponent();
      };
      return (
        <Form.Item
          name={field}
          colon={colon}
          {...itemProps}
          label={renderLabelHelpMessage()}
          rules={handleRules()}
          labelCol={labelCol}
          wrapperCol={wrapperCol}
        >
          {() => getContent()}
        </Form.Item>
      );
    }
    return () => {
      const { colProps = {}, colSlot, renderColContent, component } = props.schema;
      if (!componentMap.has(component)) return null;
      const { baseColProps = {} } = props.formProps;
 
      const realColProps = { ...baseColProps, ...colProps };
 
      const { isIfShow, isShow } = unref(getShowRef);
 
      const getContent = () => {
        return colSlot
          ? getSlot(slots, colSlot)
          : renderColContent
          ? renderColContent(unref(getValuesRef))
          : renderItem();
      };
      return (
        isIfShow && (
          <Col {...realColProps} class={!isShow ? 'hidden' : ''}>
            {() => getContent()}
          </Col>
        )
      );
    };
  },
});