刘光辉
11 小时以前 0dfe84494048ce27ba8449831782128412d3eb13
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
<script lang="ts" setup>
import type { ItemCfg } from './types/genItem';
 
import { computed, nextTick, onMounted, reactive, ref, toRefs, unref, watch } from 'vue';
 
import { useAttrs, useMessage } from '@jnpf/hooks';
import { ScrollContainer } from '@jnpf/ui';
import { useModal } from '@jnpf/ui/modal';
 
import { upperFirst } from 'lodash-es';
 
import { getPrintDevSelector } from '#/api/system/printDev';
import { getDataModelFieldList } from '#/api/systemData/dataModel';
import { getDictionaryTypeSelector } from '#/api/systemData/dictionary';
import { useGeneratorStore } from '#/store';
 
import FieldModal from './components/FieldModal.vue';
import FormAttrPane from './components/FormAttrPane.vue';
import FormScript from './components/FormScript.vue';
import StylePane from './components/StylePane.vue';
import { inputComponents, layoutComponents, ocrComponents, selectComponents, systemComponents } from './helper/componentMap';
import { noTableAllowList, noVModelList, ocrList, vModelIgnoreList } from './helper/config';
import { convertControlType, replaceControlData, sortControlTypeOptionsByUsage } from './helper/controlType';
import { setVirtualField, setVirtualTable } from './helper/displayOnly';
import { layoutList, orgList, systemList } from './helper/rightPanel';
import * as RightComp from './rightComponents';
 
defineOptions({ inheritAttrs: false });
const props = defineProps(['activeData', 'formConf', 'drawingList', 'formInfo', 'dbType']);
const emit = defineEmits(['controlTypeChange']);
defineExpose({ setTabActiveKey });
const attrs = useAttrs({ excludeDefaultKeys: false });
const storageTypeOptions = [
  { id: 0, fullName: '展示数据' },
  { id: 1, fullName: '存储数据' },
];
const VNodes = (_, { attrs }) => attrs.vnodes;
const generatorStore = useGeneratorStore();
const { createMessage } = useMessage();
const [registerFieldModal, { openModal: openFieldModal }] = useModal();
const [registerScriptModal, { openModal: openScriptModal }] = useModal();
const fieldSelectRef = ref(null);
const childFieldSelectRef = ref(null);
const state = reactive({
  activeKey: 'field',
  fieldOptions: [],
  dictionaryOptions: [],
  printTplOptions: [],
  activeFunc: '',
  activeScriptType: 'fieldEvent',
  activeRegIndex: -1,
});
const { activeKey, fieldOptions, printTplOptions } = toRefs(state);
const getBindValue = computed(() => ({ ...props, toggleVmodelCase }));
const config = computed<ItemCfg>(() => unref(props.activeData).__config__);
const jnpfKey = computed(() => unref(props.activeData).__config__?.jnpfKey);
const getCompName = computed(() => {
  const allComps = [...inputComponents, ...selectComponents, ...systemComponents, ...layoutComponents, ...ocrComponents];
  const comp = allComps.filter((o) => o.__config__.jnpfKey === unref(jnpfKey));
  if (!comp.length) return '';
  return comp[0]?.__config__.label;
});
const controlTypeOptions = computed(() => {
  const components = [...inputComponents, ...selectComponents].filter(
    (item) => item.__config__.layout === 'colFormItem' && !noVModelList.includes(item.__config__.jnpfKey),
  );
  const availableComponents = props.activeData?.__config__?.isSubTable
    ? components.filter((item) => !noTableAllowList.includes(item.__config__.jnpfKey))
    : components;
  const options = availableComponents.map((item) => ({ id: item.__config__.jnpfKey, fullName: item.__config__.label }));
  return sortControlTypeOptionsByUsage(options);
});
const canChangeControlType = computed(() => controlTypeOptions.value.some((item) => item.id === unref(jnpfKey)));
const getRightComp = computed(() => {
  if (!unref(jnpfKey)) return null;
  if (orgList.includes(unref(jnpfKey))) return RightComp.ROrgRight;
  if (unref(jnpfKey) === 'popupTableSelect') return RightComp.RPopupSelect;
  if (ocrList.includes(unref(jnpfKey))) return RightComp.ROcr;
  return RightComp[`R${upperFirst(unref(jnpfKey))}`];
});
const drawingOptions = computed(() => {
  const list: any[] = [];
  const loop = (data, parent?) => {
    if (!data) return;
    if (data.__config__ && data.__config__.jnpfKey !== 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
      loop(data.__config__.children, data);
    }
    if (Array.isArray(data)) data.forEach((d) => loop(d, parent));
    if (data.__vModel__ && data.__config__.jnpfKey !== 'table') {
      list.push({ id: data.__vModel__, fullName: data.__config__.label });
    }
  };
  loop(unref(props.drawingList));
  return list;
});
const getRightCompBind = computed(() => ({
  activeData: props.activeData,
  dicOptions: state.dictionaryOptions,
  ...unref(attrs),
  drawingOptions: unref(drawingOptions),
  drawingList: props.drawingList,
  formInfo: unref(props.formInfo),
  onUseDetailVisibleRuleChange,
  editDetailVisibleRule,
  onUseDetailFormatRuleChange,
  editDetailFormatRule,
  editValidateRule,
  onUseTableRowReadonlyChange,
  editTableRowReadonlyRule,
}));
const scriptDemoType = computed(() => {
  if (state.activeScriptType === 'detailVisibleRule') return 'detailVisibleRule';
  if (state.activeScriptType === 'detailFormatRule') return 'detailFormatRule';
  if (state.activeScriptType === 'tableRowReadonlyRule') return 'tableRowReadonlyRule';
  if (state.activeScriptType === 'validateRule') return 'validateRule';
  return 'formField';
});
const showControlStateConfig = computed(() => {
  const key = unref(jnpfKey);
  return (layoutList.includes(key) || vModelIgnoreList.includes(key)) && !['tableGridTd', 'tableGridTr'].includes(key);
});
const showAuditLog = computed(() => {
  const key = unref(jnpfKey);
  return (
    !props.activeData?.__config__?.isDisplayOnly &&
    !props.activeData?.__config__?.isVirtualField &&
    key !== 'input' &&
    ((!!props.activeData?.__vModel__ && !noVModelList.includes(key)) || !!props.activeData?.isStorage)
  );
});
const showDisplayOnlyConfig = computed(() => {
  const config = props.activeData?.__config__;
  return config?.layout === 'colFormItem' && props.activeData?.__vModel__ !== undefined && !noVModelList.includes(unref(jnpfKey)) && !config.isVirtualField;
});
const showVirtualFieldConfig = computed(() => {
  const config = props.activeData?.__config__;
  return (
    (config?.layout === 'colFormItem' && props.activeData?.__vModel__ !== undefined && !noVModelList.includes(unref(jnpfKey))) || unref(jnpfKey) === 'table'
  );
});
const getHasTable = computed(() => generatorStore.getHasTable);
const getAllTable = computed({
  get() {
    return generatorStore.getAllTable;
  },
  set(val) {
    generatorStore.setAllTable(val);
  },
});
const getSubTable = computed({
  get() {
    return generatorStore.getSubTable;
  },
  set(val) {
    generatorStore.setSubTable(val);
  },
});
const getFormItemList = computed({
  get() {
    return generatorStore.getFormItemList;
  },
  set(val) {
    generatorStore.setFormItemList(val);
  },
});
const getMainTable = computed(() => {
  const allTable = unref(getAllTable);
  const item = allTable.find((o) => o.typeId == '1');
  if (!item || !item.table) return '';
  return item.table;
});
const fieldText = computed(() => {
  return '不能使用【系统自动生成】字段,如:tenantid、id、foreignid、flowid、flowtaskid、deleteuserid、deletetime、deletemark、version、tenant_id、foreign_id、flow_id、flow_task_id、delete_user_id、delete_time、delete_mark、f_tenant_id、f_id、f_foreign_id、f_flow_id、f_flow_task_id、f_delete_user_id、f_delete_time、f_delete_mark、f_version';
});
 
watch(
  () => unref(props.formConf),
  (val) => {
    if (val.formStyle === 'word-form' && val.labelPosition === 'top') {
      val.labelPosition = 'left';
    }
  },
  { deep: true },
);
watch(
  () => unref(props.activeData),
  (val) => {
    if (!val || !val.__config__) return;
    if (!val.__config__.tableName && val.__config__.jnpfKey !== 'table') {
      val.__config__.tableName = unref(getMainTable);
    }
    setDefaultOptions();
  },
);
function getSubTableField(key) {
  let item: Recordable = {};
  const list = unref(getSubTable).filter((o) => o.table === key);
  if (list.length) {
    item = list[0];
  }
  let arr = [];
  if (item && item.fields) {
    arr = item.fields.filter((o) => o.primaryKey != 1).map((o) => ({ ...o, fullName: o.fieldName ? `${o.field}(${o.fieldName})` : o.field }));
  }
  return arr;
}
function onChildTableFieldChange(val, formId) {
  if (!val) return (props.activeData.__vModel__ = '');
  let boo = false;
  const loop = (list) => {
    for (const e of list) {
      const config = e.__config__;
      if (config.jnpfKey === 'table' && config.tableName === props.activeData.__config__.relationTable) {
        for (let j = 0; j < config.children.length; j++) {
          const child = config.children[j];
          if (child.__vModel__ === val && child.__config__.formId !== formId) {
            boo = true;
            break;
          }
        }
      }
      if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
        loop(config.children);
      }
    }
  };
  loop(unref(props.drawingList));
  if (boo) {
    createMessage.warning(`子表字段【${val}】已存在,请重新选择!`);
    props.activeData.__vModel__ = undefined;
    nextTick(() => {
      props.activeData.__vModel__ = '';
    });
    return;
  }
  const options: any[] = getSubTableField(props.activeData.__config__.relationTable);
  const item = options.find((o) => o.field == val);
  if (!item || !item.fieldName) return;
  props.activeData.__config__.label = item.fieldName;
}
function onFieldChange(val, formId) {
  if (!val) return (props.activeData.__vModel__ = '');
  let boo = false;
  const loop = (list) => {
    for (const e of list) {
      const config = e.__config__;
      if (e.__vModel__ === val && e.__config__.formId !== formId) {
        boo = true;
        break;
      }
      if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
        loop(config.children);
      }
    }
  };
  loop(unref(props.drawingList));
  if (boo) {
    createMessage.warning(`字段【${val}】已存在,请重新选择!`);
    props.activeData.__vModel__ = undefined;
    nextTick(() => {
      props.activeData.__vModel__ = '';
    });
    return;
  }
  const item = (state.fieldOptions as any[]).find((o) => o.realField == val);
  if (!item || !item.fieldName) return;
  props.activeData.__config__.label = item.fieldName;
}
function onInputFieldChange(val, formId, parentVModel) {
  if (!val) return;
  // eslint-disable-next-line regexp/no-unused-capturing-group
  const RegExp = /(^_([a-z0-9]_?)*$)|(^[a-z](_?[a-z0-9])*_?$)/i;
  if (!RegExp.test(val)) {
    createMessage.warning(`请输入正确的字段`);
    return;
  }
  let boo = false;
  let childBoo = false;
  if (parentVModel) {
    const loop = (data, parent?) => {
      if (!data) return;
      if (data.__config__ && data.__config__.children && Array.isArray(data.__config__.children)) {
        loop(data.__config__.children, data);
      }
      if (Array.isArray(data)) data.forEach((d) => loop(d, parent));
      if (
        parent?.__config__?.jnpfKey == 'table' &&
        data.__vModel__ &&
        data.__vModel__.toLowerCase() === val.toLowerCase() &&
        data.__config__.formId !== formId &&
        data.__config__.parentVModel === parentVModel
      ) {
        childBoo = true;
      }
    };
    loop(unref(props.drawingList));
  } else {
    const loop = (data, parent?) => {
      if (!data) return;
      if (data.__config__?.jnpfKey !== 'table' && data.__config__?.children && Array.isArray(data.__config__.children)) {
        loop(data.__config__.children, data);
      }
      if (Array.isArray(data)) data.forEach((d) => loop(d, parent));
      if (data.__vModel__ && data.__vModel__.toLowerCase() === val.toLowerCase() && data.__config__.formId !== formId) {
        boo = true;
      }
    };
    loop(unref(props.drawingList));
  }
  if (boo) {
    createMessage.warning(`字段【${val}】已存在,请重新输入!`);
    props.activeData.__vModel__ = '';
    return;
  }
  if (childBoo) {
    createMessage.warning(`子表字段【${val}】已存在,请重新输入!`);
    props.activeData.__vModel__ = '';
    return;
  }
  props.activeData.__vModel__ = toggleVmodelCase(val);
}
function onVirtualFieldChange(checked) {
  if (unref(jnpfKey) === 'table') return setVirtualTable(props.activeData, checked);
  setVirtualField(props.activeData, checked);
}
function onControlKeyChange(val, formId, parentVModel) {
  if (!val) return;
  // eslint-disable-next-line regexp/no-unused-capturing-group
  const fieldPattern = /(^_([a-z0-9]_?)*$)|(^[a-z](_?[a-z0-9])*_?$)/i;
  if (!fieldPattern.test(val)) {
    createMessage.warning('请输入正确的控件字段');
    props.activeData.controlKey = '';
    return;
  }
  let duplicated = false;
  const loop = (data, parent?) => {
    if (!data || duplicated) return;
    if (Array.isArray(data)) return data.forEach((item) => loop(item, parent));
    const config = data.__config__;
    const isSameScope = parentVModel ? parent?.__config__?.jnpfKey === 'table' && config?.parentVModel === parentVModel : !config?.isSubTable;
    const dataKey = config?.isVirtualField ? data.controlKey : data.__vModel__;
    if (isSameScope && dataKey?.toLowerCase() === val.toLowerCase() && config?.formId !== formId) duplicated = true;
    if (Array.isArray(config?.children)) loop(config.children, data);
  };
  loop(unref(props.drawingList));
  if (duplicated) {
    createMessage.warning(`${parentVModel ? '子表' : ''}字段【${val}】已存在,请重新输入!`);
    props.activeData.controlKey = '';
    return;
  }
  props.activeData.controlKey = val;
  if (props.activeData.__config__.jnpfKey === 'table') {
    props.activeData.__config__.children?.forEach((child) => {
      child.__config__.parentVModel = val;
    });
  }
}
function toggleVmodelCase(str) {
  const dbType = props.dbType || '';
  if (dbType.toLowerCase() === 'Oracle'.toLowerCase() || dbType.toLowerCase() === 'DM'.toLowerCase()) {
    return str.toUpperCase();
  }
  if (dbType.toLowerCase() === 'PostgreSQL'.toLowerCase() || dbType.toLowerCase() === 'KingBaseES'.toLowerCase()) {
    return str.toLowerCase();
  }
  return str;
}
function onStorageChange(val) {
  if (val == 0) {
    props.activeData.__vModel__ = '';
    props.activeData.__config__.noShow = false;
  } else {
    if (unref(getHasTable)) {
      if (props.activeData.__config__.isSubTable && !props.activeData.__config__.relationTable) {
        const loop = (data, parent?) => {
          if (!data) return;
          if (data.__config__ && data.__config__.jnpfKey !== 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
            loop(data.__config__.children, data);
          }
          if (Array.isArray(data)) data.forEach((d) => loop(d, parent));
          if (data.__vModel__ === props.activeData.__config__.parentVModel) {
            props.activeData.__config__.relationTable = data.__config__.tableName;
          }
        };
        loop(unref(props.drawingList));
      }
      setDefaultOptions();
    } else {
      props.activeData.__vModel__ = toggleVmodelCase(
        `${props.activeData.__config__.jnpfKey}Field${props.activeData.__config__.formId.replace('formItem', '')}`,
      );
    }
  }
}
function onTableChange() {
  props.activeData.__vModel__ = '';
  setDefaultOptions();
}
// 设计子表关联子表变化
function onChildTableNameChange(tableName, formId) {
  if (!tableName) return;
  const drawingList = unref(props.drawingList) || [];
  let boo = false;
  const loop = (list) => {
    for (const e of list) {
      const config = e.__config__;
      if (config.jnpfKey === 'table' && config.tableName === tableName && config.formId !== formId) {
        boo = true;
        break;
      }
      if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
        loop(config.children);
      }
    }
  };
  loop(drawingList);
  if (boo) {
    createMessage.warning(`子表【${tableName}】已存在,请重新选择!`);
    props.activeData.__config__.tableName = undefined;
    nextTick(() => {
      props.activeData.__config__.tableName = '';
    });
    return;
  }
  for (let i = 0; i < props.activeData.__config__.children.length; i++) {
    const child = props.activeData.__config__.children[i];
    child.__config__.relationTable = child.__config__.isVirtualField ? '' : tableName;
    if (!child.__config__.isVirtualField) child.__vModel__ = '';
  }
}
function onTableNameChange(val) {
  if (val) props.activeData.__config__.tableName = toggleVmodelCase(val);
}
function setDefaultOptions() {
  if (!unref(getHasTable)) return;
  let fieldOptions: any[] = [];
  if ((props.activeData.__vModel__ === undefined && props.activeData.isStorage != 1) || props.activeData.__config__.jnpfKey === 'table') return;
  if (!props.activeData.__config__.tableName || props.activeData.__config__.tableName === unref(getMainTable)) {
    fieldOptions = getFormItemList.value.map((o) => ({ ...o, realField: o.field }));
  } else {
    const list = unref(getAllTable).filter((o) => o.table === props.activeData.__config__.tableName);
    if (list.length) {
      const item = list[0];
      const options = item.fields.map((o) => ({
        ...o,
        realField: `jnpf_${props.activeData.__config__.tableName}_jnpf_${o.field}`,
      }));
      fieldOptions = options;
    } else {
      props.activeData.__config__.tableName = unref(getMainTable);
      fieldOptions = getFormItemList.value.map((o) => ({ ...o, realField: o.field }));
      props.activeData.__vModel__ = '';
    }
  }
  (state.fieldOptions as any[]) = fieldOptions
    .filter((o) => o.primaryKey != 1)
    .map((o) => ({ ...o, fullName: o.fieldName ? `${o.field}(${o.fieldName})` : o.field }));
}
function handleAddField() {
  let tableName = '';
  if (props.activeData.__config__.isSubTable) {
    tableName = props.activeData.__config__.relationTable;
    (unref(childFieldSelectRef) as any)?.getSelectRef().blur();
  } else {
    tableName = props.activeData.__config__.tableName;
    (unref(fieldSelectRef) as any)?.getSelectRef().blur();
  }
  const linkId = props.formInfo.dbLinkId || '0';
  setTimeout(() => {
    openFieldModal(true, { linkId, tableName });
  }, 200);
}
async function updateFieldOptions() {
  let tableName = '';
  tableName = props.activeData.__config__.isSubTable ? props.activeData.__config__.relationTable : props.activeData.__config__.tableName;
  const type = props.formInfo.type;
  const queryType = type == 3 || type == 4 || type == 5 ? '1' : '0';
  const res = await getDataModelFieldList(props.formInfo.dbLinkId, tableName, queryType);
  const fields = res.data.list;
  for (let i = 0; i < getAllTable.value.length; i++) {
    if (getAllTable.value[i].table === tableName) {
      getAllTable.value[i].fields = fields;
      break;
    }
  }
  if (props.activeData.__config__.isSubTable) {
    getSubTable.value = getAllTable.value.filter((o) => o.typeId == '0');
  } else {
    if (props.activeData.__config__.tableName === unref(getMainTable)) getFormItemList.value = fields;
    setDefaultOptions();
  }
}
function getFuncText(key) {
  let text = '';
  switch (key) {
    case 'blur': {
      text = '失去焦点时触发';
      break;
    }
    case 'change': {
      text = '发生变化时触发';
      break;
    }
    case 'click': {
      text = '点击时触发';
      break;
    }
    case 'tabClick': {
      text = '面板点击时触发';
      break;
    }
    default: {
      text = '';
      break;
    }
  }
  return text;
}
function editFunc(funcName) {
  state.activeFunc = funcName;
  state.activeScriptType = 'fieldEvent';
  openScriptModal(true, { text: props.activeData.on[state.activeFunc] });
}
function onUseDetailVisibleRuleChange(val) {
  if (!val || props.activeData.__config__.detailVisibleRule) return;
  props.activeData.__config__.detailVisibleRule =
    '({ formData, field, value, item, config, onlineUtils }) => {\n    // 返回 true 显示当前字段,返回 false 隐藏当前字段\n    return true\n}';
}
function editDetailVisibleRule() {
  state.activeScriptType = 'detailVisibleRule';
  const defaultScript =
    props.activeData.__config__.detailVisibleRule ||
    '({ formData, field, value, item, config, onlineUtils }) => {\n    // 返回 true 显示当前字段,返回 false 隐藏当前字段\n    return true\n}';
  openScriptModal(true, { text: defaultScript });
}
function onUseDetailFormatRuleChange(val) {
  if (!val || props.activeData.__config__.detailFormatRule) return;
  props.activeData.__config__.detailFormatRule =
    '({ formData, field, value, item, config, onlineUtils }) => {\n    // 返回格式化后的字段值\n    return value\n}';
}
function editDetailFormatRule() {
  state.activeScriptType = 'detailFormatRule';
  const defaultScript =
    props.activeData.__config__.detailFormatRule ||
    '({ formData, field, value, item, config, onlineUtils }) => {\n    // 返回格式化后的字段值\n    return value\n}';
  openScriptModal(true, { text: defaultScript });
}
function onUseTableRowReadonlyChange(val) {
  if (!val || props.activeData.rowReadonlyFunc) return;
  props.activeData.rowReadonlyFunc =
    '({ row, rowIndex, formData, onlineUtils }) => {\n    // 返回 true 时当前子表行只读,返回 false 时保持可编辑\n    return false\n}';
}
function editTableRowReadonlyRule() {
  state.activeScriptType = 'tableRowReadonlyRule';
  const defaultScript =
    props.activeData.rowReadonlyFunc ||
    '({ row, rowIndex, formData, onlineUtils }) => {\n    // 返回 true 时当前子表行只读,返回 false 时保持可编辑\n    return false\n}';
  openScriptModal(true, { text: defaultScript });
}
function editValidateRule(index) {
  state.activeRegIndex = index;
  state.activeScriptType = 'validateRule';
  const item = props.activeData.__config__.regList[index] || {};
  const defaultScript =
    item.validatorFunc ||
    '({ value, formData, field, rowIndex, rowData, item, config, onlineUtils }) => {\n    // rowIndex/rowData 仅在子表中可用\n    // 返回 true 校验通过,返回 false 校验失败\n    return true\n}';
  openScriptModal(true, { text: defaultScript });
}
function updateScript(data) {
  openScriptModal();
  if (state.activeScriptType === 'detailVisibleRule') {
    props.activeData.__config__.detailVisibleRule = data;
    return;
  }
  if (state.activeScriptType === 'detailFormatRule') {
    props.activeData.__config__.detailFormatRule = data;
    return;
  }
  if (state.activeScriptType === 'tableRowReadonlyRule') {
    props.activeData.rowReadonlyFunc = data;
    return;
  }
  if (state.activeScriptType === 'validateRule') {
    const item = props.activeData.__config__.regList[state.activeRegIndex];
    if (item) item.validatorFunc = data;
    return;
  }
  props.activeData.on[state.activeFunc] = data;
}
function getDictionaryType() {
  getDictionaryTypeSelector().then((res) => {
    state.dictionaryOptions = res.data.list.filter((o) => o.children && o.children.length);
  });
}
function getPrintTplList() {
  getPrintDevSelector().then((res) => {
    state.printTplOptions = res.data.list.filter((o) => o.children && o.children.length).map((o) => ({ ...o, hasChildren: true }));
  });
}
function hasTipLabel(jnpfKey) {
  return ![...layoutList, ...systemList].includes(jnpfKey) || ['billRule', 'card', 'table'].includes(jnpfKey);
}
function setTabActiveKey(data) {
  state.activeKey = data;
}
function onControlTypeChange(key) {
  if (!key || key === unref(jnpfKey)) return;
  const target = [...inputComponents, ...selectComponents].find((item) => item.__config__.jnpfKey === key);
  if (!target) return;
  replaceControlData(props.activeData, convertControlType(props.activeData, target));
  setDefaultOptions();
  emit('controlTypeChange');
}
 
onMounted(() => {
  getDictionaryType();
  getPrintTplList();
  if (!props.activeData || !props.activeData.__config__) return;
  if (!props.activeData.__config__.tableName && props.activeData.__config__.jnpfKey !== 'table') {
    props.activeData.__config__.tableName = unref(getMainTable);
  }
  setDefaultOptions();
});
</script>
<template>
  <div class="right-board common-board">
    <a-tabs v-model:active-key="activeKey" :tab-bar-gutter="14" class="average-tabs">
      <a-tab-pane key="field" tab="组件属性" />
      <a-tab-pane key="style" tab="组件样式" />
      <a-tab-pane key="form" tab="表单属性" v-if="!formInfo.isKit" />
    </a-tabs>
    <div class="field-box" v-if="activeData?.__config__ && activeData.__config__.jnpfKey">
      <ScrollContainer>
        <a-form :colon="false" layout="vertical" v-show="activeKey === 'field'" class="right-board-form">
          <a-form-item label="控件类型" v-if="!['tableGridTr', 'tableGridTd'].includes(activeData.__config__.jnpfKey)">
            <jnpf-select :value="jnpfKey" :options="controlTypeOptions" show-search @change="onControlTypeChange" v-if="canChangeControlType" />
            <a-input :value="getCompName" disabled v-else />
          </a-form-item>
          <a-form-item label="控件用途" v-if="['calculate', 'dateCalculate'].includes(jnpfKey)">
            <jnpf-select v-model:value="activeData.isStorage" :options="storageTypeOptions" @change="onStorageChange" />
          </a-form-item>
          <a-form-item v-if="showDisplayOnlyConfig">
            <template #label>是否为展示字段<BasicHelp text="绑定并读取数据库字段,但该字段不会随表单提交保存" /></template>
            <a-switch v-model:checked="activeData.__config__.isDisplayOnly" />
          </a-form-item>
          <a-form-item label="是否为虚拟字段" v-if="showVirtualFieldConfig">
            <a-switch
              v-model:checked="activeData.__config__.isVirtualField"
              :disabled="activeData.__config__.isVirtualFieldInherited"
              @change="onVirtualFieldChange" />
          </a-form-item>
          <a-form-item v-if="showVirtualFieldConfig && config.isVirtualField">
            <template #label>控件字段<BasicHelp text="虚拟字段不关联数据库,提交时不会写入该字段名称和值" /></template>
            <jnpf-input
              v-model:value="activeData.controlKey"
              placeholder="请输入自定义字段"
              @change="onControlKeyChange($event, config.formId, config.parentVModel)" />
          </a-form-item>
          <div v-if="!config.isVirtualField && ((activeData.__vModel__ !== undefined && !noVModelList.includes(jnpfKey)) || activeData.isStorage)">
            <div v-if="getHasTable">
              <div v-if="!config.isSubTable">
                <a-form-item label="数据库表" v-if="jnpfKey !== 'table'">
                  <jnpf-select
                    v-model:value="activeData.__config__.tableName"
                    placeholder="请选择"
                    show-search
                    :dropdown-match-select-width="false"
                    :options="getAllTable.map((o) => ({ ...o, fullName: o.tableName ? `${o.table}(${o.tableName})` : o.table }))"
                    :field-names="{ value: 'table' }"
                    @change="onTableChange">
                    <template #option="{ fullName, typeId }">
                      <span class="custom-option-left"> {{ fullName }}</span>
                      <span class="custom-option-right">{{ typeId == '1' ? '主表' : '从表' }}</span>
                    </template>
                  </jnpf-select>
                </a-form-item>
                <a-form-item>
                  <template #label>控件字段<BasicHelp :text="fieldText" /></template>
                  <jnpf-input v-model:value="activeData.__vModel__" disabled v-if="jnpfKey === 'table'" />
                  <jnpf-select
                    v-model:value="activeData.__vModel__"
                    ref="fieldSelectRef"
                    placeholder="请输入数据库字段"
                    :options="fieldOptions"
                    :dropdown-match-select-width="false"
                    show-search
                    allow-clear
                    :field-names="{ value: 'realField' }"
                    @change="onFieldChange($event, config.formId)"
                    v-else>
                    <template #dropdownRender="{ menuNode: menu }">
                      <VNodes :vnodes="menu" />
                      <a-divider class="my-[4px]" />
                      <div class="select-item-add" @mousedown="(e) => e.preventDefault()" @click="handleAddField">
                        <a-button type="link" pre-icon="icon-ym icon-ym-btn-add">添加字段</a-button>
                      </div>
                    </template>
                  </jnpf-select>
                </a-form-item>
              </div>
              <div v-else>
                <a-form-item label="数据库表">
                  <jnpf-select
                    v-model:value="activeData.__config__.relationTable"
                    placeholder="请选择"
                    :options="getAllTable.map((o) => ({ ...o, fullName: o.tableName ? `${o.table}(${o.tableName})` : o.table }))"
                    :field-names="{ value: 'table' }"
                    show-search
                    disabled />
                </a-form-item>
                <a-form-item>
                  <template #label>控件字段<BasicHelp :text="fieldText" /></template>
                  <jnpf-select
                    v-model:value="activeData.__vModel__"
                    ref="childFieldSelectRef"
                    placeholder="请输入数据库字段"
                    :options="getSubTableField(config.relationTable)"
                    :dropdown-match-select-width="false"
                    show-search
                    allow-clear
                    :field-names="{ value: 'field' }"
                    @change="onChildTableFieldChange($event, config.formId)">
                    <template #dropdownRender="{ menuNode: menu }">
                      <VNodes :vnodes="menu" />
                      <a-divider class="my-[4px]" />
                      <div class="select-item-add" @mousedown="(e) => e.preventDefault()" @click="handleAddField">
                        <a-button type="link" pre-icon="icon-ym icon-ym-btn-add">添加字段</a-button>
                      </div>
                    </template>
                  </jnpf-select>
                </a-form-item>
              </div>
            </div>
            <div v-else>
              <a-form-item>
                <template #label>控件字段<BasicHelp :text="fieldText" /></template>
                <jnpf-input
                  v-model:value="activeData.__vModel__"
                  placeholder="请输入数据库字段"
                  :disabled="jnpfKey === 'table' || !!formInfo.isKit"
                  @change="onInputFieldChange($event, config.formId, config.parentVModel)" />
              </a-form-item>
            </div>
          </div>
          <a-form-item label="控件标题" v-if="!layoutList.includes(jnpfKey) || jnpfKey === 'table'">
            <jnpf-i18n-input v-model:value="activeData.__config__.label" v-model:i18n="activeData.__config__.labelI18nCode" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="显示标题" v-if="!layoutList.includes(jnpfKey)">
            <a-switch v-model:checked="activeData.__config__.showLabel" />
          </a-form-item>
          <a-form-item label="显示标题" v-if="jnpfKey === 'table'">
            <a-switch v-model:checked="activeData.__config__.showTitle" />
          </a-form-item>
          <a-form-item label="卡片标题" v-if="jnpfKey === 'card'">
            <jnpf-i18n-input v-model:value="activeData.header" v-model:i18n="activeData.headerI18nCode" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="标题提示" v-if="hasTipLabel(jnpfKey)">
            <jnpf-i18n-input v-model:value="activeData.__config__.tipLabel" v-model:i18n="activeData.__config__.tipLabelI18nCode" placeholder="请输入" />
          </a-form-item>
          <div v-if="showControlStateConfig">
            <a-form-item label="控件标识">
              <a-input v-model:value="activeData.controlKey" placeholder="请输入" />
            </a-form-item>
            <a-form-item label="是否隐藏">
              <a-switch v-model:checked="activeData.__config__.noShow" />
            </a-form-item>
          </div>
          <a-form-item label="占位提示" v-if="activeData.placeholder !== undefined && !systemList.includes(jnpfKey)">
            <jnpf-i18n-input v-model:value="activeData.placeholder" v-model:i18n="activeData.placeholderI18nCode" placeholder="请输入" />
          </a-form-item>
          <div v-if="jnpfKey === 'table' && !config.isVirtualField">
            <a-form-item label="关联子表" v-if="getHasTable">
              <jnpf-select
                v-model:value="activeData.__config__.tableName"
                placeholder="请选择"
                show-search
                :dropdown-match-select-width="false"
                :options="getSubTable.map((o) => ({ ...o, fullName: o.tableName ? `${o.table}(${o.tableName})` : o.table }))"
                :field-names="{ value: 'table' }"
                @change="onChildTableNameChange($event, config.formId)">
                <template #option="{ fullName, typeId }">
                  <span class="custom-option-left"> {{ fullName }}</span>
                  <span class="custom-option-right">{{ typeId == '1' ? '主表' : '从表' }}</span>
                </template>
              </jnpf-select>
            </a-form-item>
            <a-form-item v-if="!getHasTable && !formInfo.isKit">
              <template #label>关联子表<BasicHelp text="发布后,关联子表的数据库表名不支持修改" /></template>
              <jnpf-input v-model:value="activeData.__config__.tableName" placeholder="请输入" allow-clear :maxlength="50" @change="onTableNameChange" />
            </a-form-item>
          </div>
          <component :is="getRightComp" v-bind="getRightCompBind" :key="activeData.__config__.renderKey" />
          <div v-if="![...layoutList, ...noVModelList, 'relationQuery'].includes(jnpfKey) && jnpfKey !== 'input'">
            <a-form-item label="是否禁用" v-if="!systemList.includes(jnpfKey) && !activeData.__config__.isDisplayOnly">
              <a-switch v-model:checked="activeData.disabled" />
            </a-form-item>
            <a-form-item label="是否必填" v-if="!systemList.includes(jnpfKey) && !activeData.__config__.isDisplayOnly">
              <a-switch v-model:checked="activeData.__config__.required" />
            </a-form-item>
            <a-form-item label="是否隐藏">
              <a-switch v-model:checked="activeData.__config__.noShow" />
            </a-form-item>
          </div>
          <a-form-item label="是否隐藏" v-if="['relationFormAttr', 'popupAttr', 'calculate', 'dateCalculate'].includes(jnpfKey) && activeData.isStorage">
            <a-switch v-model:checked="activeData.__config__.noShow" />
          </a-form-item>
          <a-form-item label="详情显示规则" v-if="jnpfKey !== 'input' && !['tableGridTr', 'tableGridTd'].includes(jnpfKey)">
            <a-switch v-model:checked="activeData.__config__.useDetailVisibleRule" @change="onUseDetailVisibleRuleChange" />
          </a-form-item>
          <a-form-item v-if="jnpfKey !== 'input' && activeData.__config__.useDetailVisibleRule && !['tableGridTr', 'tableGridTd'].includes(jnpfKey)">
            <template #label>自定义规则<BasicHelp text="仅影响详情页。脚本返回 true 显示当前字段,返回 false 隐藏当前字段。" /></template>
            <a-button block @click="editDetailVisibleRule">编辑规则</a-button>
          </a-form-item>
          <a-form-item label="详情格式化规则" v-if="jnpfKey !== 'input' && !['tableGridTr', 'tableGridTd'].includes(jnpfKey)">
            <a-switch v-model:checked="activeData.__config__.useDetailFormatRule" @change="onUseDetailFormatRuleChange" />
          </a-form-item>
          <a-form-item v-if="jnpfKey !== 'input' && activeData.__config__.useDetailFormatRule && !['tableGridTr', 'tableGridTd'].includes(jnpfKey)">
            <template #label>自定义规则<BasicHelp text="仅影响详情页。脚本返回格式化后的字段值。" /></template>
            <a-button block @click="editDetailFormatRule">编辑规则</a-button>
          </a-form-item>
          <a-form-item label="启用审计日志" v-if="showAuditLog">
            <a-switch v-model:checked="activeData.__config__.biz_log_enabled" />
          </a-form-item>
          <div v-if="activeData.on">
            <a-divider>脚本事件<BasicHelp text="不支持代码生成" /></a-divider>
            <a-form-item :label="key" v-for="(_value, key) in activeData.on" :key="key">
              <a-button block @click="editFunc(key)">{{ getFuncText(key) }}</a-button>
            </a-form-item>
          </div>
        </a-form>
        <StylePane v-bind="getBindValue" v-show="activeKey === 'style'" />
        <FormAttrPane v-bind="getBindValue" :print-tpl-options="printTplOptions" v-show="activeKey === 'form'" />
      </ScrollContainer>
    </div>
    <FieldModal @register="registerFieldModal" @update-options="updateFieldOptions" />
    <FormScript @register="registerScriptModal" :tree-title="formInfo.fullName" :drawing-list="drawingList" :type="scriptDemoType" @confirm="updateScript" />
  </div>
</template>