田源
2023-09-21 249ef0d4a5b5011927d1b73ad7e05284258ec11a
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
<!-- eslint-disable vue/valid-v-for -->
<!-- eslint-disable vue/require-v-for-key -->
<template>
  <div>
    <avue-form
      v-model="form"
      :option="option"
      v-loading="loading"
      ref="form"
      :style="{ minHeight: loading ? '300px' : '' }"
      :key="updateIndex"
    >
      <template :slot="item.prop + 'Label'" v-for="item in slotColumnList">
        <span>
          <span>{{ item.label }} </span>
          <el-tooltip
            v-if="item.keyAttr"
            class="item"
            effect="dark"
            content="该属性为关键属性"
            placement="top-start"
          >
            <i class="el-icon-star-on key_attr_icon"></i>
          </el-tooltip>
        </span>
      </template>
      <template :slot="item.prop + ''" v-for="item in slotColumnList">
        <vciWebRefer
          :key="item.prop" :data-key="item.prop"
          v-if="item.type == 'refer'"
          :referConfig="item.referConfig || {}"
          :value="form[item.referConfig.field] || item.value"
          :text="form[item.referConfig.showField]"
          :disabled="item.disabled"
          :display="item.display"
          @setReferValue="setReferValue"
        ></vciWebRefer>
      </template>
    </avue-form>
  </div>
</template>
 
<script>
import { getFormDetail } from "@/api/formTemplate";
import { getDictionary } from "../../api/system/dict";
import vciWebRefer from "../refer/vciWebRefer.vue";
export default {
  name: "FormTemplate",
  components: { vciWebRefer },
  props: {
    // 默认禁用元素
    disabledProp: {
      type: Array,
      default: () => ["id", "lcstatus"],
    },
    templateOid: {
      type: String,
      default: "",
    },
    codeClassifyOid: {
      type: String,
      default: "",
    },
    // 列表数据oid
    rowOid: {
      type: String,
      default: "",
    },
    // 表单类型(add, edit, detail)
    type: {
      type: String,
      default: "add",
    },
    // 自定义表单类型
    selfColumnType: {
      type: Object,
      default: () => ({}),
    },
    // 自定义表单属性
    selfColumnConfig: {
      type: Object,
      default: () => ({}),
    },
    // 一行放几个表单
    trendsSpan: {
      type: Number,
      default: 8,
    },
    TreeValue:{
      type: String,
      default: "",
    },
    eventList:{
      type:Array
    }
  },
  data() {
    return {
      eventFlag:{},
      TreeValueForm:'',
      updateIndex: 0,
      form: {},
      option: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: "140",
        column: [],
        group: [],
      },
      loading: true,
      columnType: {
        text: "input",
        combox: "select",
        truefalse: "switch",
        number: "number",
        textarea: "textarea",
        datetime: "datetime",
        date: "date",
        refer: "refer",
      },
      defaultValue: {},
      // 表单属性
      attributes: [],
      slotColumnList: [],
    };
  },
  mounted() {
    this.handleResize();
  },
  created() {
 
  },
  computed: {
    localTrendsSpan() {
      if (this.trendsSpan) {
        return this.trendsSpan;
      } else {
        let windowWidth = document.body.clientWidth;
        return 24 / Math.floor(windowWidth / 500);
      }
    },
 
  },
  watch: {
    // 表单数据修改反馈到父组件
    form: {
      deep: true,
      immediate: true,
      handler(newV) {
        this.$emit("getFormData", newV);
      },
    },
    TreeValue:{
      handler(newval,oldval){
        if(newval){
          this.TreeValueForm=newval;
        }
      },
      deep:true,
      immediate:true
    }
  },
  methods: {
    // 渲染表单模板
    templateRender(formItemList,TreeValue) {
      if (this.eventList) {
        this.eventFlag= this.eventList.some(item => {
          if (item.classifyInvokeEditFlag === 'true') {
            this.eventObject = item;
            return true;
          }
        });
      }
      // 无需分组数据
      let column = [];
      let group = [];
      let dictKeys = [];
      let slotColumnList = [];
      formItemList.forEach((formItem) => {
        formItem = this.resetFormConfig(formItem);
        if (formItem.type === "line") {
          group.push({
            label: formItem.text,
            prop: formItem.text,
            collapse: true,
            column: [],
          });
          return;
        }
        if (
          formItem.type === "combox" &&
          formItem.comboxKey &&
          (!Array.isArray(formItem.dicData) || formItem.dicData.length === 0) &&
          (!Array.isArray(formItem.data) || formItem.data.length === 0)
        ) {
          dictKeys.push({ dictKey: formItem.comboxKey, field: formItem.field });
        }
        // 禁用部分属性(外部传值禁用和参照禁用)
        if (this.disabledProp.includes(formItem.field)) {
          formItem.readOnly = true;
        }
        if (formItem.field == "lcstatus") {
          formItem.field = formItem.field + "_text";
          formItem.readOnly = true;
        }
        // 设置表单校验的规则,文本
        let message = "请选择";
        let trigger = "change";
        if (formItem.type === "text") {
          message = "请输入";
          trigger = "blur";
        }
        let fieldMapKey=''
        if( formItem.type == "refer"){
          if(!formItem.fieldMap){
            fieldMapKey=formItem.field+'Id'
          }
        }
        let columnItem = {
          label: formItem.text,
          labelslot: true,
          prop: this.$utilFunc.isValuableObj(formItem.referConfig)
            ? formItem.showField || formItem.field
            : formItem.field,
          field: formItem.field,
          type: this.columnType[formItem.type],
          dicData: this.getDataList(formItem.type, formItem.data),
          disabled: this.type === "detail" ? true : formItem.readOnly || (formItem.codeValueApplyStatus && formItem.codeValueApplyStatus == 2 ?true : false) ,
          prepend: this.preOrSufFixShow("text", formItem.prefix),
          append: this.preOrSufFixShow("text", formItem.suffix),
          prefixIcon: this.preOrSufFixShow("icon", formItem.prefix),
          suffixIcon: this.preOrSufFixShow("icon", formItem.suffix),
          valueFormat:formItem.dateFormate,
          format: formItem.dateFormate,
          keyAttr: formItem.keyAttr,
          value: (formItem.dicData && formItem.dicData.length > 0 && formItem.secType == "codefixedsec" ? formItem.dicData[0].id : null) ||
            (formItem.secType == "codedatesec"?formItem.codeDateValue: null) || ( TreeValue&& formItem.secType == "codelevelsec" ? TreeValue : null) ,
          placeholder: formItem.inputTip,
          comboxKey: formItem.comboxKey,
          tip: formItem.tooltips,
          // hidden:formItem.secType && formItem.codeValueApplyStatus == 3 ? true : false,
          // readonly:formItem.codeValueApplyStatus && formItem.codeValueApplyStatus == 2 ?true : false ,
          display: !formItem.hidden,
          maxlength: formItem.maxlength,
          filterable: true,
          referConfig:
            formItem.type == "refer"
              ? {
                title: formItem.text,
                showField: formItem.showField || formItem.field,
                field: formItem.field,
                fieldMap:formItem.fieldMap || {fieldMapKey:'id'},
                placeholder: formItem.inputTip,
                options: formItem.referConfig
              }
              : {},
          span: formItem.span
            ? formItem.span
            : formItem.type === "textarea"
              ? 24
              : this.localTrendsSpan,
          rules: [
            {
              required: formItem.required,
              message: `${message}${formItem.text}`,
              trigger,
            },
            {
              // 如果没有正则则匹配任何字符
              pattern: formItem.verify ? formItem.verify : /[\s\S.]*/g,
              message: formItem.tooltips,
              trigger,
            },
          ],
          props: {
            label: "value",
            value: "key",
          },
        };
        slotColumnList.push(columnItem);
        if (group.length === 0) {
          column.push(columnItem);
        } else {
          group[group.length - 1]["column"].push(columnItem);
        }
      });
      this.slotColumnList = slotColumnList;
      this.$set(this.option, "column", column);
      this.$set(this.option, "group", group);
      this.updateIndex++;
      if (this.type === "add") {
        this.loading = false;
      }
 
      this.geDictData(dictKeys);
      this.getFormDetail();
      // console.log('selfColumnConfig',this.selfColumnConfig)
 
    },
    // 使用传入的表单数据配置
    resetFormConfig(formItem) {
      for (const configType in this.selfColumnConfig) {
        if (Object.hasOwnProperty.call(this.selfColumnConfig, configType)) {
          const element = this.selfColumnConfig[configType];
          if (configType === "function") {
            for (const attr in element) {
              if (Object.hasOwnProperty.call(element, attr)) {
                const fun = element[attr];
                formItem[attr] = fun(formItem);
              }
            }
          } else if (configType === "exchange") {
            for (const newAttr in element) {
              if (Object.hasOwnProperty.call(element, newAttr)) {
                const oldAttr = element[newAttr];
                formItem[newAttr] = formItem[oldAttr];
              }
            }
          } else if (configType === "directVoluation") {
            for (const attr in element) {
              if (Object.hasOwnProperty.call(element, attr)) {
                const value = element[attr];
                formItem[attr] = value;
              }
            }
          }
        }
      }
      return formItem;
    },
    // 根据屏幕动态配置表单布局
    handleResize() {
      // let windowWidth = document.body.clientWidth;
      // this.trendsSpan = 24 / Math.floor(windowWidth / 500);
      // this.updateIndex++;
    },
    // 前后缀
    preOrSufFixShow(type, val) {
      if (this.$utilFunc.isEmpty(val) && typeof val !== "string") return;
      const isIcon = val.slice(0, 8) === "el-icon-";
      if ((type === "text" && !isIcon) || (type === "icon" && isIcon)) {
        return val;
      }
    },
    // 获取swich和已拿到的下拉数据
    getDataList(type, dicData) {
      if (type === "truefalse") {
        return [
          {
            key: false,
            value: "否",
          },
          {
            key: true,
            value: "是",
          },
        ];
      } else if (type === "combox") {
        return dicData;
      }
      return [];
    },
    // 异步获取字典数据
    geDictData(dictKeys) {
      dictKeys.forEach((dictObj) => {
        getDictionary({ code: dictObj.dictKey }).then((res) => {
          if (res.data && res.data.code === 200) {
            this.option.column = this.option.column.map((item) => {
              if (item.field === dictObj.field) {
                let dictData = (res.data.data || []).map((itm) => {
                  itm.value = itm.dictValue;
                  itm.key = itm.dictKey;
                  return itm;
                });
                item.dicData = dictData;
              }
              return item;
            });
          }
        });
      });
    },
    // 表单校验
    validate() {
      return new Promise((resolve) => {
        this.$refs.form.validate((valid, done) => {
          if (valid) {
            done();
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    // 获取表单详情数据
    getFormDetail() {
      if (this.type === "add") return;
      getFormDetail({ templateOid: this.templateOid, oid: this.rowOid }).then(
        (res) => {
          this.form = Object.assign(this.form, res.data.data[0]);
          this.loading = false;
        }
      );
    },
    setReferValue(data) {
      debugger;
      if (data.field) {
        this.form[data.field] = data.value || "";
        this.form[data.showField] = data.text || "";
        if (data.fieldMap) {
          //说明需要映射
          for (let key in data.fieldMap) {
            let mapFields = data.fieldMap[key].split(",");
            let value = [];
            data.rawData.forEach(_item => {
              var temp;
              if (!_item.attributes) {
                _item.attributes = _item;
              }
              if (!_item.attributes.data) {
                _item.attributes.data = {};
              }
              if (mapFields.length == 1) {
                var mapField = mapFields[0];
                if (mapField.indexOf("attribute.") > -1) {
                  temp = _item['attributes'][mapField.subString("attribute.".length)] || _item['attributes']['data'][mapField.subString("attribute.".length)];
                } else {
                  temp = _item['attributes'][mapField] ||_item['attributes']['data'][mapField] || _item[mapField];
                }
              } else {
                //有多个
                var mutiTemp = [];
                layui.each(mapFields, function (_indexField, _itemField) {
                  if (_itemField.indexOf("attribute.") > -1) {
                    mutiTemp.push(_item['attributes'][_itemField.subString("attribute.".length)] || _item['attributes']['data'][_itemField.subString("attribute.".length)]);
                  } else {
                    mutiTemp.push(_item['attributes'][_itemField] || _item['attributes']['data'][_itemField] || _item[_itemField]);
                  }
                });
                temp = mutiTemp.join(' ');
              }
              if (temp != null && temp != '') {
                value.push(temp);
              }
            })
            this.form[key] = value.join(',');
          }
        }
        this.$emit("getFormData", this.form);
        this.$emit("referConfigDataUpdate", data);
      }
    },
  },
};
</script>
 
<style lang="scss" scoped>
.key_attr_icon {
  font-size: 20px !important;
  vertical-align: baseline;
  color: red;
}
</style>