zhaoxiaoqiang1
2026-01-04 f1d30d03186c79ca2cbcfe60d6d2ce7d73fba97b
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
/*
 * @Author: lixiong
 * @Date: 2019-08-20 09:41:24
 * @Last Modified by: Pengjiantian
 * @Last Modified time: 2020-06-02 15:09:05
 */
import dayjs from 'dayjs'
import CommFetch from '@/utils/core/commFetch'
import { Message } from 'element-ui'
 
/**
 * ApiModel 接口映射模型
 */
 
export default class ApiModel {
  /**
   * constructor 初始化
   * @param {Object} options 配置项 @example
   * {
   *  api: '接口地址',  // required
   *  formList: [ // 表单映射信息(通常用来渲染表单)
   *    {
   *      type: 'input',label: '客户名称:',value: '',name: 'customerName'
   *    }
   *  ],
   *  responseMap: [ // 接口响应映射信息(通常用来表格或类似表单展示的数据)
   *  {
   *    label: '车位首付(元)',field: 'downpayparkingamount',isMoney: true,isDesc: true
   *  }
   * ],
   * computedResponse: item => {
   *    return {...item}
   * },
   * computedItem: item => {
   *    return {...item}
   * },
   *
   */
 
  constructor(options = {}) {
    const { baseConf, fetchConf = {}, ...other } = options
    // 默认日期格式
    this.dateFormate = 'YYYY/MM/DD'
 
    this.ruleAction = (rule, message) => {
      if (typeof rule === 'string') {
        if (rule === 'required') {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (value.toString().trim() === '') {
              callback(new Error(message || '该字段必填'))
            } else {
              callback()
            }
            callback()
          }
        }
        if (rule === 'phone') {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (!/1\d{10}/.test(value)) {
              callback(new Error('手机号格式有误'))
            } else {
              callback()
            }
          }
        }
        if (rule === 'number') {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (isNaN(value)) {
              callback(new Error('必须输入数字'))
            } else {
              callback()
            }
          }
        }
        // 身份证录入校验
        if (rule === 'idCart') {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            const RegExp = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
            if (!RegExp.test(value)) {
              callback(new Error('身份证输入有误'))
            } else {
              callback()
            }
          }
        }
      }
 
      if (typeof rule === 'object') {
        let { required, pattern, maxLength, minLength } = rule
        if (required) {
          return (rule, value, callback) => {
            // console.log(value)
            value = this.getItemValue(value)
            if (value === '') {
              callback(new Error('该字段必填'))
            } else {
              callback()
            }
          }
        }
 
        if (maxLength) {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (value.length > maxLength) {
              callback(new Error(`最多输入${maxLength}个字符`))
            } else {
              callback()
            }
          }
        }
 
        if (minLength) {
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (value.length < minLength) {
              callback(new Error(`最少输入${minLength}个字符`))
            } else {
              callback()
            }
          }
        }
 
        if (pattern) {
          if (pattern === 'string') {
            pattern = new RegExp(pattern)
          }
 
          return (rule, value, callback) => {
            value = this.getItemValue(value)
            if (!pattern.test(value)) {
              callback(new Error('输入格式有误'))
            } else {
              callback()
            }
          }
        }
      }
      return false
    }
 
    this.commFetch = new CommFetch(baseConf, fetchConf)
    this.setOptions(other)
  }
 
  getItemValue(value) {
    if (Array.isArray(value)) {
      return value.join('')
    }
    return (value || '').trim()
  }
 
  /**
   * 获取表单信息
   * @param {Object} initValues 初始值对象
   */
  getFormList(initValues = {}, list) {
    const { formList } = this
    if (typeof list === 'undefined') {
      list = [...formList]
    }
    const keys = Object.keys(initValues)
    if (keys.length > 0) {
      return list.reduce((pre, curr) => {
        let { value, name, descName, descValue, children } = curr
        if (typeof value === 'undefined' && Array.isArray(children)) {
          // has children
          pre.push({
            ...curr,
            children: this.getFormList(initValues, children)
          })
        } else {
          let result = { ...curr }
          result.value =
            typeof initValues[name] === 'undefined' ? value : initValues[name]
          if (typeof descValue === 'undefined' && descName) {
            const dValue = initValues[descName]
            result.descValue = typeof dValue === 'undefined' ? '' : dValue
          }
          pre.push(result)
        }
        return pre
      }, [])
    }
    return [...list]
  }
 
  // 获取表单数据值
  getFormValues(list) {
    const { formList } = this
    if (typeof list === 'undefined') {
      list = [...formList]
    }
    return list.reduce((pre, curr) => {
      const { name, names, value, children } = curr
      // 父级不包含value,则取子级
      if (typeof value === 'undefined' && Array.isArray(children)) {
        children.forEach(subItem => {
          const { name: subName, value: subValue } = subItem
          pre[subName] = this.formatInput(subValue, subName, list)
        })
      } else if (Array.isArray(names) && Array.isArray(value)) {
        // 将数组值传送到names字段对应的key中
        names.forEach((subName, index) => {
          pre[subName] = this.formatInput(value[index] || '', subName, list)
        })
        pre[name] = this.formatInput(value, name, list)
      } else {
        pre[name] = this.formatInput(value, name, list)
      }
      return pre
    }, {})
  }
 
  // 获取表单验证规则
  getFormRules(list) {
    const { formList } = this
    if (typeof list === 'undefined') {
      list = [...formList]
    }
    return list.reduce((pre, curr) => {
      const { rules = [], name, children, attrs = [] } = curr
      if (Array.isArray(children)) {
        pre = {
          ...pre,
          ...this.getFormRules(children)
        }
      } else {
        const ruleArray = rules.reduce((rulePre, ruleCurr) => {
          if (this.getRule(ruleCurr)) {
            rulePre.push(this.getRule(ruleCurr))
          }
          return rulePre
        }, [])
        if (ruleArray.length > 0) {
          const requiredRule = ruleArray.find(({ required }) => required)
          if (
            requiredRule &&
            !ruleArray.some(({ trigger }) => trigger === 'change') &&
            !attrs.some(attr => attr === 'multiple')
          ) {
            // change 多选初始会显示错误信息,临时不加change
            ruleArray.push({ ...requiredRule, trigger: 'change' })
          }
          pre[name] = ruleArray
        }
      }
      return pre
    }, {})
  }
 
  getRule(rule) {
    if (typeof rule === 'string') {
      // rule: required phone number
      const temp = rule === 'required' ? { required: true } : {}
      return {
        validator: this.ruleAction(rule),
        ...temp,
        trigger: 'blur'
      }
    }
    if (typeof rule === 'object') {
      const { validator, trigger = 'blur', message } = rule
      if (typeof validator === 'function') {
        return {
          trigger,
          ...rule
        }
      } else {
        return {
          trigger,
          ...rule,
          validator: this.ruleAction(rule, message)
        }
      }
    }
    return false
  }
 
  // 统一输出数据格式,如日期格式化
  formatInput(val, name, list) {
    const { dateFormate } = this
    if (typeof this.computedValue === 'function') {getRule
      val = this.computedValue(val, name, list)
    }
    if (Array.isArray(val) && val.length > 0) {
      return val.reduce((pre, curr) => {
        pre.push(this.formatInput(curr, name, list))
        return pre
      }, [])
    }
    if (val instanceof Date) {
      val = dayjs(val).format(dateFormate)
    }
    return val
  }
 
  /**
   * 获取表格信息
   */
  getTableList() {
    const { tableList } = this
    return [...tableList]
  }
 
  /**
   * post 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   */
  post(body = {}, conf = {}) {
    return this.toRequest(body, {
      method: 'post',
      ...conf
    })
  }
 
  /**
   * post 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   */
  upload(body = {}, conf = { headers: false }) {
    const formData = this.getFormData(body)
    return this.toRequest(formData, {
      method: 'post',
      ...conf
    })
  }
 
  /**
   * post 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   */
  submit(body = {}, conf = {}) {
    const { api } = this
    const tempForm = document.createElement('form')
    tempForm.method = 'post'
    tempForm.target = '_blank'
    tempForm.action = this.commFetch.mixApi(api)
 
    document.body.appendChild(tempForm)
 
    Object.keys(body).forEach(key => {
      const tempInput = document.createElement('input')
      tempInput.type = 'hidden'
      tempInput.name = key
      tempInput.value = body[key]
      tempForm.appendChild(tempInput)
    })
    tempForm.submit()
    document.body.removeChild(tempForm)
  }
 
  exportFile(body = {}, conf = {}) {
    const { api } = this
    const url = `${process.env.VUE_APP_API_ORIGIN}${process.env.VUE_APP_API_PREFIX}${api}`
    return new Promise((resolve, reject) => {
      fetch(url, {
        credentials: 'include', // 跨域请求中需要带有cookie
        method: 'POST',
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
        body: JSON.stringify(body), // 自动修改请求头,formdata的默认请求头的格式是 multipart/form-data
      }).then(async (res) => {
        let newRes = res.clone();
        const resText = await res.text();
        if (resText.indexOf('code') != -1) {
          const t = JSON.parse(resText);
          Message.warning(t.msg);
          this.excelLoading = false;
          throw `${t.msg}`;
        } else {
          newRes.blob().then((blob) => {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = `${dayjs().format(
              'YYYYMMDDhhmmss'
            )}.xlsx`;
            link.click();
            window.URL.revokeObjectURL(link.href);
          });
          Message({
            message: '导出成功,请等待下载结果文件!',
            type: 'success',
          });
        }
        resolve(true)
      }).catch(err => {
        resolve(false)
 
      });
    })
  }
 
  getFormData(body) {
    let formData = null
    if (typeof body === 'object' && !(body instanceof FormData)) {
      formData = new FormData()
      Object.keys(body).forEach(key => {
        formData.append(key, body[key])
      })
    }
    return formData === null ? body : formData
  }
 
  /**
   * get 请求处理
   * @param {String} api 接口地址
   * @param {Object|String} body 请求参数
   */
  get(body = {}, conf = {}) {
    return this.toRequest(body, {
      method: 'get',
      ...conf
    })
  }
 
  // 遍历options内容到实例
  setOptions(options) {
    Object.keys(options).forEach(key => {
      this[key] = options[key]
    })
  }
 
  // 请求统一处理
  toRequest(body = {}, conf = {}) {
    const { api } = this
    return new Promise((resolve, reject) => {
      this.commFetch
        .fetch(api, body, conf)
        .then(res => {
          resolve(this.formateResponse(res))
        })
        .catch(reson => {
          reject(reson)
        })
    })
  }
 
  // 输出数据统一处理(这里为将列表项转换为list字段值)
  formateResponse(res) {
    let { result = {}, code, ext, msg, ...other } = res
    // let list = {}
    if (Array.isArray(result)) {
      result = {
        list: this.computedList(result)
      }
    } else {
      const { records, ...other } = result
      if (Array.isArray(records)) {
        result = {
          list: this.computedList(records),
          ...other
        }
      }
    }
    const temp = {
      ...other,
      ...result
    }
    if (typeof this.computedResponse === 'function') {
      // 响应数据的进一步处理
      return this.computedResponse(temp)
    }
    return temp
  }
 
  // 列表数据处理
  computedList(list = []) {
    const { computedItem } = this
    if (typeof computedItem === 'function') {
      return list.reduce((pre, curr) => {
        pre.push(this.computedItem(curr))
        return pre
      }, [])
    }
    return [...list]
  }
}