刘光辉
5 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
<script lang="ts" setup>
/**
 * 培训任务表单(对齐说明书 6.2.18)
 * - 空白新增 = 临时培训:内容字段可填
 * - 计划带出任务(年计划/岗计划等):编号/来源只读,其余内容与执行信息均可维护后发布
 */
import type { TaskEntity, TaskFile, TaskQuiz } from './types';
 
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
 
import { useMessage } from '@jnpf/hooks';
import { BasicForm, useForm } from '@jnpf/ui/form';
 
import { Alert as AAlert, Steps as ASteps } from 'ant-design-vue';
import dayjs from 'dayjs';
 
import { launchFlow } from '#/api/onlineDev/visualDev';
import { getCoursePaperOptions } from '#/api/x/tms/course';
import { getPlaceOptions } from '#/api/x/tms/place';
import { createTask, getTaskInfo, publishTask, updateTask } from '#/api/x/tms/task';
import { getTrainerOptions } from '#/api/x/tms/trainer';
import { JnpfPopupSelect } from '#/components/Jnpf/popupSelect';
import { TMS_DIC_FIELD_NAMES } from '#/views/x/tms/shared/dic';
import { TMS_BTN } from '#/views/x/tms/shared/ui';
 
import {
  EVAL_MODE_OPTIONS,
  SOURCE_TYPE_OPTIONS,
  TASK_CATEGORY_OPTIONS,
  TASK_KIND_OPTIONS,
  TRAIN_MODE_OPTIONS,
  YES_NO_OPTIONS,
  labelOfPublishStatus,
  loadTaskDics,
} from './constants';
import { TMS_TASK_SUBMIT_FLOW, buildTaskSubmitLaunchDataList } from './flow';
 
defineOptions({ name: 'TmsTaskForm' });
 
const DT_FMT = 'YYYY-MM-DD HH:mm:ss';
/** 点选日期时,时分秒默认 00:00:00(否则 ant DatePicker 会带当前时刻) */
const TIME_ZERO = dayjs('00:00:00', 'HH:mm:ss');
const dateTimePickerProps = {
  showTime: { defaultValue: TIME_ZERO },
  format: DT_FMT,
  valueFormat: DT_FMT,
  style: { width: '100%' },
};
 
/** 日期组件校验类型是 number,字符串会被当成空值 */
function toTimeNumber(value?: null | number | string) {
  if (value == null || value === '') return undefined;
  if (typeof value === 'number' && !Number.isNaN(value)) return value;
  const text = String(value).trim();
  if (/^\d{10,13}$/.test(text)) {
    const n = Number(text);
    return text.length === 10 ? n * 1000 : n;
  }
  const date = dayjs(text);
  return date.isValid() ? date.valueOf() : undefined;
}
 
function formatTaskTime(value?: null | number | string) {
  if (value == null || value === '') return undefined;
  const date = dayjs(value);
  return date.isValid() ? date.format(DT_FMT) : undefined;
}
/** 可由空白新增的来源(说明书:临时;文件等由系统带出) */
const BLANK_CREATE_SOURCES = new Set(['temp']);
 
const route = useRoute();
const router = useRouter();
const { createMessage } = useMessage();
 
const loading = ref(false);
const submitting = ref(false);
const paperOptions = ref<{ fullName: string; id: string }[]>([]);
const placeOptions = ref<{ fullName: string; id: string; placeNo?: string }[]>([]);
const trainerOptions = ref<{ fullName: string; id: string; archiveNo?: string }[]>([]);
/** 非草稿等场景锁内容;计划带出默认可改 */
const contentLocked = ref(false);
const taskFiles = ref<TaskFile[]>([]);
const uploadFiles = ref<any[]>([]);
const taskQuizzes = ref<TaskQuiz[]>([]);
const currentEvalMode = ref('');
const showQuizPreset = computed(() => currentEvalMode.value === 'quiz');
const showPracticeTip = computed(() => currentEvalMode.value === 'practice');
 
/** 来自计划/系统带出:主题等内容只读 */
const fromPlan = ref(false);
/** 1=培训内容 2=执行安排 */
const currentStep = ref(1);
const state = reactive({ id: '', publishStatus: 'draft' as string });
 
const isEdit = computed(() => !!route.params.id && route.params.id !== 'create');
const pageTitle = computed(() => {
  if (!isEdit.value) return '新增临时培训任务';
  return fromPlan.value ? '维护培训任务(计划带出)' : '编辑临时培训任务';
});
const tipText = computed(() => {
  if (currentStep.value === 1) {
    if (fromPlan.value) {
      return '计划已带出主题、方式、对象等;可继续补全或修改后进入下一步。编号与来源不可改。';
    }
    return '先填写培训内容,下一步再安排时间、地点、试卷等执行信息。';
  }
  if (showPracticeTip.value) {
    return '实操考核发布后,需在培训记录详情中由培训师现场打分。';
  }
  if (showQuizPreset.value) {
    return '提问考核须配置提问预设;学员签到后弹题作答。';
  }
  if (fromPlan.value) {
    return '请补全执行安排后保存或发布。可返回上一步修改培训内容。';
  }
  return '请填写执行安排;可返回上一步修改培训内容。';
});
const stepItems = computed(() => [
  { title: fromPlan.value ? '计划内容(可维护)' : '培训内容' },
  { title: fromPlan.value ? '执行安排(发布)' : '执行安排' },
]);
 
const fileColumns = [
  { title: '编号', dataIndex: 'fileNo', width: 160 },
  { title: '文件名称', dataIndex: 'fileName' },
  { title: '可下载', dataIndex: 'canDownload', width: 90 },
  { title: '操作', dataIndex: 'action', width: 80 },
];
 
const quizColumns = [
  { title: '序号', dataIndex: 'sortNo', width: 70 },
  { title: '问题', dataIndex: 'question' },
  { title: '参考答案', dataIndex: 'answer', width: 220 },
  { title: '操作', dataIndex: 'action', width: 80 },
];
 
const [registerContentForm, contentFormApi] = useForm({
  labelWidth: 120,
  baseColProps: { span: 12 },
  schemas: [
    {
      field: 'taskNo',
      label: '培训编号',
      component: 'Input',
      componentProps: { disabled: true, placeholder: '草稿号保存生成,发布后正式编号' },
    },
    {
      field: 'publishStatusLabel',
      label: '发布状态',
      component: 'Input',
      componentProps: { disabled: true },
      ifShow: () => isEdit.value,
    },
    {
      field: 'sourceType',
      label: '来源类型',
      component: 'Select',
      defaultValue: 'temp',
      componentProps: {
        disabled: true,
        options: [],
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'category',
      label: '培训分类',
      component: 'Select',
      defaultValue: 'temp',
      componentProps: {
        disabled: true,
        options: [],
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'sourcePlanNo',
      label: '来源计划号',
      component: 'Input',
      componentProps: { disabled: true, placeholder: '计划带出' },
      ifShow: () => fromPlan.value,
    },
    {
      field: 'subject',
      label: '培训主题',
      component: 'Input',
      componentProps: { placeholder: '请输入培训主题', maxlength: 200 },
      rules: [{ required: true, message: '必填', trigger: 'blur' }],
    },
    {
      field: 'trainMode',
      label: '培训方式',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '请选择',
        options: [],
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => syncModeRules(val),
      },
      rules: [{ required: true, message: '必填', trigger: 'change' }],
    },
    {
      field: 'evalMode',
      label: '考核方式',
      component: 'Select',
      componentProps: {
        allowClear: true,
        placeholder: '请选择',
        options: [],
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => syncEvalRules(val),
      },
      rules: [{ required: true, message: '必填', trigger: 'change' }],
    },
    {
      field: 'teacherId',
      label: '培训师',
      component: 'Select',
      componentProps: {
        allowClear: true,
        showSearch: true,
        placeholder: '请选择培训师(培训师管理)',
        options: [],
        optionFilterProp: 'fullName',
        fieldNames: { label: 'fullName', value: 'id' },
      },
    },
    {
      field: 'traineeIds',
      label: '培训对象',
      component: 'UserSelect',
      componentProps: { placeholder: '请选择培训对象', multiple: true },
      rules: [{ required: true, type: 'array', min: 1, message: '必填', trigger: 'change' }],
    },
    {
      field: 'materialId',
      label: '培训教材',
      component: 'Input',
      render: ({ model }) =>
        h(JnpfPopupSelect, {
          columnOptions: [
            { label: '教材编号', value: 'materialno' },
            { label: '教材名称', value: 'fullname' },
            {
              label: '文件类型',
              value: 'filetype',
              jnpfKey: 'select',
              props: { label: 'fullName', value: 'enCode' },
              __config__: {
                jnpfKey: 'select',
                dataType: 'dictionary',
                dictionaryType: 'tmsdt008',
              },
            },
          ],
          disabled: contentLocked.value,
          hasPage: true,
          pageSize: 20,
          interfaceId: '871690100000000001',
          placeholder: '请选择培训教材',
          popupTitle: '选择数据',
          popupType: 'popover',
          popupWidth: '800px',
          propsValue: 'id',
          relationField: 'fullname',
          value: model.materialId || undefined,
          'onUpdate:value': (id?: string) => {
            contentFormApi.setFieldsValue({ materialId: id || undefined });
            contentFormApi.clearValidate(['materialId']);
            if (!id) return;
          },
          onChange: (_id: string, row: any) => {
            const data = row || {};
            contentFormApi.setFieldsValue({
              materialNo: data.materialno || undefined,
            });
            ensureMainFile(data);
          },
        }),
    },
    {
      field: 'taskKind',
      label: '任务类型',
      component: 'Select',
      defaultValue: 'new',
      componentProps: {
        options: [],
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'prevTaskNo',
      label: '上次任务编号',
      component: 'Input',
      componentProps: { placeholder: '再维护时由系统带出', disabled: true },
      ifShow: ({ values }) => values.taskKind === 'continue',
    },
    {
      field: 'keyPoints',
      label: '培训要点',
      component: 'Textarea',
      colProps: { span: 24 },
      componentProps: { rows: 2, placeholder: '选填', maxlength: 2000 },
    },
  ],
});
 
const [registerExecForm, execFormApi] = useForm({
  labelWidth: 120,
  baseColProps: { span: 12 },
  schemas: [
    {
      field: 'startTime',
      label: '开始时间',
      component: 'DatePicker',
      componentProps: dateTimePickerProps,
      rules: [{ required: true, message: '必填', trigger: 'change' }],
    },
    {
      field: 'endTime',
      label: '结束时间',
      component: 'DatePicker',
      componentProps: dateTimePickerProps,
      rules: [{ required: true, message: '必填', trigger: 'change' }],
    },
    {
      field: 'closeTime',
      label: '关闭时间',
      component: 'DatePicker',
      componentProps: dateTimePickerProps,
      rules: [{ required: true, message: '必填', trigger: 'change' }],
    },
    {
      field: 'placeId',
      label: '培训地点',
      component: 'Select',
      componentProps: {
        allowClear: true,
        showSearch: true,
        placeholder: '集中/操作授课必选',
        options: [],
        optionFilterProp: 'fullName',
      },
    },
    {
      field: 'paperId',
      label: '考核试卷',
      component: 'Select',
      componentProps: {
        allowClear: true,
        showSearch: true,
        placeholder: '在线考试时必选',
        options: [],
        optionFilterProp: 'fullName',
      },
    },
    {
      field: 'evalMode',
      label: '考核方式',
      component: 'Input',
      ifShow: () => false,
    },
    {
      field: 'examStart',
      label: '考试开始',
      component: 'DatePicker',
      componentProps: dateTimePickerProps,
      ifShow: ({ values }) => values.evalMode === 'exam',
    },
    {
      field: 'examEnd',
      label: '考试结束',
      component: 'DatePicker',
      componentProps: dateTimePickerProps,
      ifShow: ({ values }) => values.evalMode === 'exam',
    },
    {
      field: 'retakeLimit',
      label: '补考次数',
      component: 'InputNumber',
      defaultValue: 1,
      componentProps: { min: 0, max: 99, precision: 0, style: { width: '100%' } },
      helpMessage: '不合格可补考次数,默认 1',
    },
    {
      field: 'passScore',
      label: '合格分',
      component: 'InputNumber',
      componentProps: { min: 0, max: 999, precision: 1, style: { width: '100%' } },
    },
    {
      field: 'quizRatio',
      label: '提问占比(%)',
      component: 'InputNumber',
      componentProps: { min: 0, max: 100, precision: 0, style: { width: '100%' } },
      helpMessage: '用于计算应提问人数:ceil(签到人数 × 占比 / 100)',
      ifShow: ({ values }) => values.evalMode === 'quiz',
    },
    {
      field: 'overdueRemind',
      label: '逾期提醒',
      component: 'Select',
      defaultValue: '0',
      componentProps: {
        options: YES_NO_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'inviteFlag',
      label: '可邀请旁听',
      component: 'Select',
      defaultValue: '0',
      componentProps: {
        options: YES_NO_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'remark',
      label: '备注',
      component: 'Textarea',
      colProps: { span: 24 },
      componentProps: { rows: 2, placeholder: '选填', maxlength: 500 },
    },
  ],
});
 
onMounted(async () => {
  loading.value = true;
  try {
    await loadTaskDics();
    await Promise.all([loadPapers(), loadPlaces(), loadTrainers()]);
    refreshOptions();
    if (isEdit.value) {
      await loadDetail(String(route.params.id));
    } else {
      fromPlan.value = false;
      contentFormApi.resetFields();
      execFormApi.resetFields();
      contentFormApi.setFieldsValue({
        sourceType: 'temp',
        category: 'temp',
        taskKind: 'new',
      });
      execFormApi.setFieldsValue({
        retakeLimit: 1,
        overdueRemind: '0',
        inviteFlag: '0',
        startTime: dayjs().startOf('day').valueOf(),
        endTime: dayjs().startOf('day').add(1, 'day').valueOf(),
        closeTime: dayjs().startOf('day').add(2, 'day').valueOf(),
      });
      applyContentEditable(true);
      currentStep.value = 1;
    }
  } finally {
    loading.value = false;
  }
});
 
watch(
  () => route.params.id,
  async (id) => {
    if (!id || id === 'create') return;
    loading.value = true;
    try {
      await loadDetail(String(id));
    } finally {
      loading.value = false;
    }
  },
);
 
function isPlanSourced(info: TaskEntity) {
  if (info.sourceId || info.sourceItemId || info.sourcePlanNo) return true;
  const st = info.sourceType || '';
  return !!st && !BLANK_CREATE_SOURCES.has(st);
}
 
function applyContentEditable(editable: boolean) {
  contentLocked.value = !editable;
  const disabled = !editable;
  contentFormApi.updateSchema([
    { field: 'subject', componentProps: { disabled, placeholder: disabled ? '' : '请输入培训主题', maxlength: 200 } },
    {
      field: 'trainMode',
      componentProps: {
        disabled,
        allowClear: !disabled,
        options: TRAIN_MODE_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => syncModeRules(val),
      },
    },
    {
      field: 'evalMode',
      componentProps: {
        disabled,
        allowClear: !disabled,
        options: EVAL_MODE_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => {
          syncEvalRules(val);
        },
      },
    },
    {
      field: 'teacherId',
      componentProps: {
        disabled,
        allowClear: !disabled,
        showSearch: !disabled,
        placeholder: '请选择培训师',
        options: trainerOptions.value,
        optionFilterProp: 'fullName',
        fieldNames: { label: 'fullName', value: 'id' },
      },
    },
    { field: 'traineeIds', componentProps: { disabled, placeholder: '请选择培训对象', multiple: true } },
    {
      field: 'taskKind',
      componentProps: {
        disabled,
        options: TASK_KIND_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    { field: 'keyPoints', componentProps: { disabled, rows: 2, placeholder: disabled ? '' : '选填', maxlength: 2000 } },
  ]);
}
 
function refreshOptions() {
  contentFormApi.updateSchema([
    {
      field: 'sourceType',
      componentProps: {
        disabled: true,
        options: SOURCE_TYPE_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'category',
      componentProps: {
        disabled: true,
        options: TASK_CATEGORY_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'trainMode',
      componentProps: {
        allowClear: true,
        options: TRAIN_MODE_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => syncModeRules(val),
      },
    },
    {
      field: 'evalMode',
      componentProps: {
        allowClear: true,
        options: EVAL_MODE_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
        onChange: (val: string) => {
          syncEvalRules(val);
        },
      },
    },
    {
      field: 'taskKind',
      componentProps: {
        options: TASK_KIND_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'teacherId',
      componentProps: {
        allowClear: true,
        showSearch: true,
        placeholder: '请选择培训师(培训师管理)',
        options: trainerOptions.value,
        optionFilterProp: 'fullName',
        fieldNames: { label: 'fullName', value: 'id' },
        disabled: contentLocked.value,
      },
    },
    {
      field: 'overdueRemind',
      componentProps: {
        options: YES_NO_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
    {
      field: 'inviteFlag',
      componentProps: {
        options: YES_NO_OPTIONS.value,
        fieldNames: TMS_DIC_FIELD_NAMES,
      },
    },
  ]);
  execFormApi.updateSchema([
    {
      field: 'placeId',
      componentProps: {
        allowClear: true,
        showSearch: true,
        options: placeOptions.value,
        optionFilterProp: 'fullName',
      },
    },
    {
      field: 'paperId',
      componentProps: {
        allowClear: true,
        showSearch: true,
        options: paperOptions.value,
        optionFilterProp: 'fullName',
      },
    },
  ]);
}
 
function syncModeRules(mode?: string) {
  const needPlace = mode === 'onsite' || mode === 'practice';
  const needMaterial = mode === 'online';
  execFormApi.updateSchema([
    {
      field: 'placeId',
      rules: needPlace ? [{ required: true, message: '现场类须选地点', trigger: 'change' }] : [],
    },
  ]);
  contentFormApi.updateSchema([
    {
      field: 'materialId',
      rules: needMaterial ? [{ required: true, message: '在线学习须选教材', trigger: 'change' }] : [],
    },
  ]);
  execFormApi.clearValidate(['placeId']);
  contentFormApi.clearValidate(['materialId']);
}
 
function ensureMainFile(row: any) {
  const materialId = row?.id;
  const fileName = row?.fullname;
  if (!materialId || !fileName) return;
  if (taskFiles.value.some((item) => item.materialId === materialId)) return;
  taskFiles.value = [
    {
      materialId,
      fileNo: row.materialno,
      fileName,
      canDownload: '0',
    },
    ...taskFiles.value,
  ];
}
 
function removeTaskFile(index: number) {
  const removed = taskFiles.value[index];
  taskFiles.value = taskFiles.value.filter((_, i) => i !== index);
  if (!removed?.fileJson) return;
  try {
    const file = JSON.parse(removed.fileJson);
    uploadFiles.value = uploadFiles.value.filter((item) => item.fileId !== file.fileId);
  } catch {
    // 非上传附件
  }
}
 
function onUploadChange(list: any[]) {
  const files = Array.isArray(list) ? list : [];
  uploadFiles.value = files;
  for (const file of files) {
    if (!file?.name) continue;
    const existed = taskFiles.value.some((row) => {
      if (!row.fileJson) return false;
      try {
        return JSON.parse(row.fileJson).fileId === file.fileId;
      } catch {
        return false;
      }
    });
    if (existed) continue;
    taskFiles.value = [
      ...taskFiles.value,
      {
        fileNo: file.fileId,
        fileName: file.name,
        fileJson: JSON.stringify(file),
        canDownload: '1',
      },
    ];
  }
}
 
function syncEvalRules(evalMode?: string) {
  currentEvalMode.value = evalMode || '';
  try {
    execFormApi.updateSchema([
      {
        field: 'paperId',
        rules: evalMode === 'exam' ? [{ required: true, message: '在线考试须选试卷', trigger: 'change' }] : [],
      },
    ]);
    execFormApi.setFieldsValue({ evalMode });
    execFormApi.clearValidate(['paperId']);
  } catch {
    // 内容步切换考核方式时执行表单可能尚未挂载
  }
  if (evalMode === 'quiz' && taskQuizzes.value.length === 0) {
    taskQuizzes.value = [{ sortNo: 1, question: '', answer: '' }];
  }
}
 
function addQuizRow() {
  taskQuizzes.value = [
    ...taskQuizzes.value,
    { sortNo: taskQuizzes.value.length + 1, question: '', answer: '' },
  ];
}
 
function removeQuizRow(index: number) {
  taskQuizzes.value = taskQuizzes.value
    .filter((_, i) => i !== index)
    .map((row, i) => ({ ...row, sortNo: i + 1 }));
}
 
async function loadPapers() {
  try {
    const list = await getCoursePaperOptions();
    paperOptions.value = (Array.isArray(list) ? list : []).map((x: any) => ({
      id: x.id,
      fullName: x.fullName || x.paperName || x.id,
    }));
  } catch {
    paperOptions.value = [];
  }
}
 
async function loadPlaces() {
  try {
    const list = await getPlaceOptions();
    placeOptions.value = (Array.isArray(list) ? list : []).map((x: any) => ({
      id: x.id,
      fullName: x.fullName || x.placeName || x.id,
      placeNo: x.placeNo,
    }));
  } catch {
    placeOptions.value = [];
  }
}
 
async function loadTrainers() {
  try {
    const list = await getTrainerOptions();
    trainerOptions.value = (Array.isArray(list) ? list : []).map((x: any) => ({
      id: x.id,
      fullName: x.fullName || x.trainerName || x.id,
      archiveNo: x.archiveNo,
    }));
  } catch {
    trainerOptions.value = [];
  }
}
 
async function loadDetail(id: string) {
  const info = await getTaskInfo(id);
  if (info.publishStatus && info.publishStatus !== 'draft') {
    createMessage.warning('仅未发布任务可编辑,已跳转详情');
    router.replace(`/tms/task/detail/${id}`);
    return;
  }
  state.id = info.id || id;
  state.publishStatus = info.publishStatus || 'draft';
  fromPlan.value = isPlanSourced(info);
  // 计划带出也从内容步开始,便于补全培训师/教材等
  currentStep.value = 1;
 
  const traineeIds = Array.isArray(info.traineeIds)
    ? info.traineeIds
    : String(info.trainees || '')
        .split(/[,;,;\s]+/)
        .filter(Boolean);
 
  contentFormApi.setFieldsValue({
    ...info,
    traineeIds,
    materialId: String(info.materialId || '').split(',')[0] || undefined,
    publishStatusLabel: labelOfPublishStatus(info.publishStatus || 'draft'),
  });
  taskFiles.value = Array.isArray(info.files) ? info.files : [];
  uploadFiles.value = taskFiles.value
    .map((row) => {
      if (!row.fileJson) return null;
      try {
        return JSON.parse(row.fileJson);
      } catch {
        return null;
      }
    })
    .filter(Boolean);
  taskQuizzes.value = Array.isArray(info.quizzes)
    ? info.quizzes.map((q, i) => ({
        ...q,
        sortNo: q.sortNo ?? i + 1,
      }))
    : [];
  execFormApi.setFieldsValue({
    ...info,
    evalMode: info.evalMode,
    startTime: toTimeNumber(info.startTime),
    endTime: toTimeNumber(info.endTime),
    closeTime: toTimeNumber(info.closeTime),
    examStart: toTimeNumber(info.examStart),
    examEnd: toTimeNumber(info.examEnd),
  });
  refreshOptions();
  // 计划带出:仅编号/来源类只读,业务内容可维护
  applyContentEditable(true);
  syncModeRules(info.trainMode);
  syncEvalRules(info.evalMode);
}
 
async function goNext() {
  try {
    await contentFormApi.validate();
    const content = contentFormApi.getFieldsValue() as TaskEntity;
    syncModeRules(content.trainMode);
    syncEvalRules(content.evalMode);
    currentStep.value = 2;
  } catch {
    // 校验失败由表单提示
  }
}
 
function goPrev() {
  currentStep.value = 1;
}
 
type SubmitMode = 'draft' | 'publish' | 'review';
 
async function handleSubmit(mode: SubmitMode | boolean = 'draft') {
  const submitMode: SubmitMode = mode === true ? 'publish' : mode === false ? 'draft' : mode;
  const [content, exec] = await Promise.all([contentFormApi.validate(), execFormApi.validate()]);
  submitting.value = true;
  try {
    let traineeIds = (content as TaskEntity).traineeIds as string | string[] | undefined;
    if (typeof traineeIds === 'string') {
      traineeIds = traineeIds.split(/[,;,;\s]+/).filter(Boolean);
    }
    const teacherRaw = (content as TaskEntity).teacherId as any;
    const materialRaw = (content as TaskEntity).materialId;
    const materialId =
      String(materialRaw || '')
        .split(/[,;,;]+/)[0]
        ?.trim() || undefined;
    const contentData = content as TaskEntity;
    const execData = exec as TaskEntity;
    const teacherId = Array.isArray(teacherRaw) ? teacherRaw[0] : teacherRaw;
    const quizzes = taskQuizzes.value
      .map((row, i) => ({
        ...row,
        sortNo: row.sortNo ?? i + 1,
        question: String(row.question || '').trim(),
        answer: String(row.answer || '').trim(),
      }))
      .filter((row) => row.question);
    if (contentData.evalMode === 'quiz' && quizzes.length === 0) {
      createMessage.warning('提问考核须至少配置一条提问预设');
      return;
    }
    // 执行表单加载时写入了整条任务,后写入会盖掉第一步改过的培训方式/考核方式
    const payload: Partial<TaskEntity> = {
      ...execData,
      ...contentData,
      sourceType: fromPlan.value ? contentData.sourceType : 'temp',
      category: fromPlan.value ? contentData.category : 'temp',
      traineeIds: Array.isArray(traineeIds) ? traineeIds : [],
      teacherId,
      materialId,
      trainMode: contentData.trainMode,
      evalMode: contentData.evalMode,
      files: taskFiles.value.filter((row) => row.fileName),
      quizzes: contentData.evalMode === 'quiz' ? quizzes : [],
      startTime: formatTaskTime(execData.startTime),
      endTime: formatTaskTime(execData.endTime),
      closeTime: formatTaskTime(execData.closeTime),
      examStart: formatTaskTime(execData.examStart),
      examEnd: formatTaskTime(execData.examEnd),
      placeId: execData.placeId,
      placeName: execData.placeName,
      paperId: execData.paperId,
      retakeLimit: execData.retakeLimit,
      passScore: execData.passScore,
      quizRatio: execData.quizRatio,
      overdueRemind: execData.overdueRemind,
      inviteFlag: execData.inviteFlag,
      remark: execData.remark,
    };
    delete (payload as any).publishStatusLabel;
 
    if (submitMode === 'review' && !teacherId) {
      createMessage.warning('送审前请选择培训师');
      return;
    }
 
    let id = state.id;
    if (isEdit.value && id) {
      await updateTask({ ...payload, id });
      if (submitMode === 'draft') createMessage.success('更新成功');
    } else {
      id = await createTask(payload);
      state.id = id || '';
      if (submitMode === 'draft') createMessage.success('创建成功');
    }
    if (!id) {
      createMessage.error('保存成功但未取得任务主键,请回到列表后再送审');
      router.push('/tms/task');
      return;
    }
    if (submitMode === 'publish') {
      await publishTask(id);
      createMessage.success('发布成功');
    }
    if (submitMode === 'review') {
      const saved = await getTaskInfo(id);
      const task = { ...payload, ...saved, id } as TaskEntity;
      await launchFlow(TMS_TASK_SUBMIT_FLOW.modelId, {
        template: TMS_TASK_SUBMIT_FLOW.templateId,
        currentUser: 1,
        customUser: 0,
        hasPermission: 0,
        dataList: buildTaskSubmitLaunchDataList(task),
      });
      createMessage.success('已送审,请培训师在待办中审批');
    }
    router.push('/tms/task');
  } catch (error: any) {
    if (error?.errorFields) return;
    createMessage.error(error?.message || '保存失败');
  } finally {
    submitting.value = false;
  }
}
 
function handleCancel() {
  router.push('/tms/task');
}
</script>
 
<template>
  <div class="jnpf-content-wrapper tms-task-form-page" v-loading="loading">
    <div class="jnpf-content-wrapper-center">
      <div class="jnpf-content-wrapper-content tms-task-form-wrap">
        <div class="tms-task-form-scroll">
          <div class="tms-task-page-title">{{ pageTitle }}</div>
          <ASteps class="tms-task-steps" size="small" :current="currentStep - 1" :items="stepItems" />
          <AAlert class="tms-task-tip" type="info" show-icon :message="tipText" />
 
          <a-card
            v-show="currentStep === 1"
            :title="fromPlan ? '计划带出(可维护)' : '培训内容'"
            :bordered="false"
            class="tms-task-section"
          >
            <BasicForm @register="registerContentForm" />
            <div class="tms-task-files">
              <div class="tms-task-files-head">
                <span>教材/附件</span>
                <JnpfUploadFile
                  v-if="!contentLocked"
                  v-model:value="uploadFiles"
                  accept="*"
                  button-text="上传附件"
                  :file-size="0"
                  :limit="0"
                  :show-all-download="false"
                  :show-upload-list="false"
                  tip-text="支持文档和视频"
                  show-tip
                  @change="onUploadChange" />
              </div>
              <a-table
                size="small"
                :pagination="false"
                row-key="materialId"
                :data-source="taskFiles"
                :columns="fileColumns">
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.dataIndex === 'fileName'">
                    <a-input v-model:value="record.fileName" :disabled="contentLocked" maxlength="300" />
                  </template>
                  <template v-else-if="column.dataIndex === 'canDownload'">
                    <a-switch
                      :checked="record.canDownload === '1'"
                      :disabled="contentLocked"
                      checked-children="是"
                      un-checked-children="否"
                      @change="(checked) => (record.canDownload = checked ? '1' : '0')" />
                  </template>
                  <template v-else-if="column.dataIndex === 'action'">
                    <a-button type="link" danger :disabled="contentLocked" @click="removeTaskFile(index)">删除</a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
 
          <a-card
            v-show="currentStep === 2"
            :title="fromPlan ? '执行安排(补全后发布)' : '执行安排'"
            :bordered="false"
            class="tms-task-section"
          >
            <BasicForm @register="registerExecForm" />
            <a-alert
              v-if="showPracticeTip"
              class="tms-task-tip"
              style="margin-top: 12px"
              type="warning"
              show-icon
              message="实操考核需培训师在培训记录中现场打分后判定完成。"
            />
          </a-card>
 
          <a-card
            v-show="currentStep === 2 && showQuizPreset"
            title="提问预设"
            :bordered="false"
            class="tms-task-section"
          >
            <a-alert
              class="tms-task-tip"
              type="info"
              show-icon
              message="考核方式为「提问」时必填至少一条;学员签到后将弹出这些问题,对照参考答案自动判分。"
            />
            <div class="tms-task-files">
              <div class="tms-task-files-head">
                <span>问题清单</span>
                <a-button type="link" @click="addQuizRow">新增问题</a-button>
              </div>
              <a-table
                size="small"
                bordered
                :pagination="false"
                row-key="sortNo"
                :data-source="taskQuizzes"
                :columns="quizColumns"
                :locale="{ emptyText: '请新增提问预设' }"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.dataIndex === 'sortNo'">
                    {{ index + 1 }}
                  </template>
                  <template v-else-if="column.dataIndex === 'question'">
                    <a-input v-model:value="record.question" maxlength="500" placeholder="请输入问题" />
                  </template>
                  <template v-else-if="column.dataIndex === 'answer'">
                    <a-input v-model:value="record.answer" maxlength="500" placeholder="参考答案(自动判分)" />
                  </template>
                  <template v-else-if="column.dataIndex === 'action'">
                    <a-button type="link" danger @click="removeQuizRow(index)">删除</a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
        </div>
 
        <div class="tms-task-form-footer">
          <a-space>
            <a-button @click="handleCancel">{{ TMS_BTN.cancel }}</a-button>
            <a-button v-if="currentStep === 2" @click="goPrev">上一步</a-button>
            <a-button v-if="currentStep === 1" type="primary" @click="goNext">下一步</a-button>
            <template v-if="currentStep === 2">
              <a-button type="primary" ghost :loading="submitting" @click="handleSubmit('draft')">
                {{ TMS_BTN.saveDraft }}
              </a-button>
              <a-button :loading="submitting" @click="handleSubmit('review')">
                {{ TMS_BTN.submitForReview }}
              </a-button>
              <a-button type="primary" :loading="submitting" @click="handleSubmit('publish')">
                {{ TMS_BTN.savePublish }}
              </a-button>
            </template>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>
 
<style scoped>
.tms-task-form-page {
  height: 100%;
  min-height: 0;
}
 
.tms-task-form-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background: #fff;
}
 
.tms-task-form-scroll {
  flex: 1;
  min-height: 0;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 16px 16px 8px;
}
 
.tms-task-page-title {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
}
 
.tms-task-steps {
  max-width: 480px;
  margin-bottom: 12px;
}
 
.tms-task-tip {
  margin-bottom: 12px;
}
 
.tms-task-section {
  margin-bottom: 12px;
}
 
.tms-task-files {
  margin-top: 8px;
}
 
.tms-task-files-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 600;
}
 
.tms-task-form-footer {
  flex-shrink: 0;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  background: #fff;
}
</style>