king
2020-09-14 76427d51a079a5fd1f45bf7188249e7a4647ae05
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
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { fromJS } from 'immutable'
import { Form, notification, Modal, Spin, Tabs } from 'antd'
import moment from 'moment'
 
import Api from '@/api'
import Utils from '@/utils/utils.js'
import SettingUtils from './utils.jsx'
import CustomScript from '@/templates/zshare/customscript'
import DataSource from './datasource'
import './index.scss'
 
const { TabPane } = Tabs
 
class SettingForm extends Component {
  static propTpyes = {
    dict: PropTypes.object,         // 字典项
    menu: PropTypes.object,         // 菜单信息
    config: PropTypes.object,       // 页面配置信息
    permFuncField: PropTypes.array, // 自定义函数可用字段
    search: PropTypes.array         // 搜索条件
  }
 
  state = {
    formlist: [],
    btnloading: false,
    activeKey: 'setting',
    search: '',
    arr_field: '',
    regoptions: [],
    setting: null,
    defaultSql: ''
  }
 
  UNSAFE_componentWillMount() {
    const { config, search } = this.props
 
    let _setting = fromJS(config.setting).toJS()
    let _scripts = _setting.scripts || []
 
    _setting.default = _setting.default || 'true'            // 默认sql
    _setting.sysInterface = _setting.sysInterface || 'false' // 是否为系统接口
    _setting.interface = _setting.sysInterface === 'true' ? (window.GLOB.mainSystemApi || '') : (_setting.interface || '')
 
    // 显示列字段,用于查询
    let columns = []
    let arr_field = []
    config.columns.forEach(col => {
      if (col.field) {
        columns.push({
          value: col.field,
          text: col.label
        })
        arr_field.push(col.field)
      }
      if (col.nameField) { // 链接的名称字段
        arr_field.push(col.nameField)
      }
    })
 
    if (_setting.primaryKey && !arr_field.includes(_setting.primaryKey)) {
      _setting.primaryKey = ''
    }
    if (!_setting.primaryKey && arr_field.length > 0) {
      arr_field.forEach(field => {
        if (field.toLowerCase() === 'id') {
          _setting.primaryKey = field
        }
      })
    }
 
    // 搜索条件,正则替换
    let allSearch = Utils.initMainSearch(search)
    allSearch = Utils.getAllSearchOptions(allSearch)
 
    // 搜索的where条件
    let _search = this.formatSearch(search)
    _search = Utils.joinMainSearchkey(_search)
 
    _search = _search.replace(/@\$@/ig, '')
    _search = _search ? 'where ' + _search : ''
 
    this.setState({
      setting: _setting,
      search: _search,
      arr_field: arr_field.join(','),
      regoptions: allSearch,
      columns: columns,
      scripts: _scripts
    })
  }
 
  /**
   * @description 获取全部搜索条件
   * @param {Array} searches 搜索条件数组
   */
  formatSearch (searches) {
    if (!searches || searches.length === 0) return []
 
    let newsearches = []
    searches.forEach(search => {
      let item = {
        key: search.field,
        match: search.match,
        type: search.type,
        label: search.label,
        value: search.initval,
        required: search.required === 'true'
      }
      if (item.type === 'group') {
        let copy = fromJS(item).toJS()
        copy.key = search.datefield
 
        item.value = search.initval && search.initval[0] ? search.initval[0] : '@$@'
        item.match = '='
        
        copy.type = 'daterange'
        copy.match = 'between'
        copy.value = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
 
        if (search.transfer === 'true') {
          newsearches.push(item)
        }
        newsearches.push(copy)
        return
      } else if (item.type === 'date') {
        item.value = moment().format('YYYY-MM-DD')
      } else if (item.type === 'datemonth') {
        item.value = moment().format('YYYY-MM')
      } else if (item.type === 'dateweek') {
        item.value = [moment().startOf('week').format('YYYY-MM-DD'), moment().endOf('week').format('YYYY-MM-DD')]
      } else if (item.type === 'daterange') {
        item.value = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      } else if (item.type === 'multiselect') {
        item.value = ['@$@']
      } else {
        item.value = '@$@'
      }
      newsearches.push(item)
    })
    
    return newsearches
  }
 
  handleConfirm = (trigger) => {
    const { activeKey, setting, scripts } = this.state
 
    if (trigger) {
      this.setState({loading: true})
    }
 
    let _scripts = scripts.filter(script => script.status !== 'false')
 
    // 表单提交时检查输入值是否正确
    if (activeKey === 'setting') {
      return new Promise((resolve, reject) => {
        this.settingForm.handleConfirm().then(res => {
          if (trigger === 'func' && res.interType !== 'inner') {
            notification.warning({
              top: 92,
              message: '使用内部接口,才可以创建存储过程!',
              duration: 5
            })
            this.setState({loading: false})
            reject()
            return
          } else if (trigger === 'interface' && res.interType !== 'system') {
            notification.warning({
              top: 92,
              message: '使用系统接口时,才可以创建接口!',
              duration: 5
            })
            this.setState({loading: false})
            reject()
            return
          } else if (res.interType === 'system' && res.default === 'false' && _scripts.length === 0) {
            notification.warning({
              top: 92,
              message: '不执行默认sql时,请添加自定义脚本!',
              duration: 5
            })
            reject()
            return
          }
 
          this.setState({
            setting: res
          }, () => {
            this.sqlverify(() => {
              this.setState({loading: false})
              resolve({...res, scripts})
            }, () => {
              this.setState({loading: false})
              reject()
            }, 'submit')
          })
        }, () => {
          this.setState({loading: false})
          reject()
        })
      })
    } else {
      return new Promise((resolve, reject) => {
        let _loading = false
        if (this.scriptsForm && this.scriptsForm.state.editItem) {
          _loading = true
        } else if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql')) {
          _loading = true
        }
  
        if (trigger === 'func' && setting.interType !== 'inner') {
          notification.warning({
            top: 92,
            message: '使用内部接口,才可以创建存储过程!',
            duration: 5
          })
          this.setState({loading: false})
          reject()
        } else if (_loading) {
          notification.warning({
            top: 92,
            message: '存在未保存脚本,请点击确定保存,或点击取消放弃修改!',
            duration: 5
          })
          this.setState({loading: false})
          reject()
        } else if (setting.interType === 'system' && setting.default === 'false' && _scripts.length === 0) {
          notification.warning({
            top: 92,
            message: '不执行默认sql时,请添加自定义脚本!',
            duration: 5
          })
          this.setState({loading: false})
          reject()
        } else {
          this.sqlverify(() => {
            this.setState({loading: false})
            resolve({...setting, scripts})
          }, () => {
            this.setState({loading: false})
            reject()
          }, 'submit')
        }
      })
    }
  }
 
  sqlverify = (_resolve, _reject, type, uscripts) => {
    const { setting, scripts, arr_field, regoptions, search } = this.state
 
    if (setting.interType !== 'system') { // 不使用系统接口时,不需要sql验证
      _resolve()
      return
    }
 
    let _scripts = []
    if (uscripts) { // 过滤禁用的脚本
      _scripts = uscripts.filter(script => script.status !== 'false')
    } else {
      _scripts = scripts.filter(script => script.status !== 'false')
    }
 
    if (type === 'setting' && setting.default === 'false') {
      _resolve()
    } else if (type === 'scripts' && _scripts.length === 0) {
      _resolve()
    } else { // type 为 submit 、 verify ,以及其他需要验证的场景
      let param = {
        func: 's_debug_sql',
        LText: SettingUtils.getDebugSql(setting, _scripts, arr_field, regoptions, search)
      }
      param.LText = Utils.formatOptions(param.LText)
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      
      Api.getLocalConfig(param).then(result => {
        if (result.status) {
          _resolve()
        } else {
          _reject()
          Modal.error({
            title: result.message
          })
        }
      })
    }
  }
 
  // 标签切换
  changeTab = (val) => {
    const { activeKey, search, arr_field } = this.state
 
    if (activeKey === 'setting') {
      let _defaultSql = ''
      this.settingForm.handleConfirm().then(res => {
        if (res.interType !== 'system') {
          notification.warning({
            top: 92,
            message: '使用系统接口时,才可以设置自定义脚本!',
            duration: 5
          })
          return
        }
 
        if (res.dataresource) {
          let _dataresource = res.dataresource
 
          if (/\s/.test(_dataresource)) {
            _dataresource = '(' + _dataresource + ') tb'
          }
 
          _defaultSql = `select top @pageSize@ ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by @orderBy@) as rows from ${_dataresource} ${search}) tmptable where rows > (@pageSize@ * (@pageIndex@ - 1)) order by tmptable.rows`
        }
        
        this.setState({
          setting: res,
          defaultSql: _defaultSql
        }, () => {
          this.setState({loading: true})
          this.sqlverify(() => { // 验证成功
            this.setState({
              activeKey: val,
              loading: false
            })
          }, () => {             // 验证失败
            this.setState({
              loading: false
            })
          }, activeKey)
        })
      })
    } else if (activeKey === 'scripts') {
      let _loading = false
      if (this.scriptsForm && this.scriptsForm.state.editItem) {
        _loading = true
      } else if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql')) {
        _loading = true
      }
 
      if (_loading) {
        notification.warning({
          top: 92,
          message: '存在未保存脚本,请点击确定保存,或点击取消放弃修改!',
          duration: 5
        })
        return
      }
    
      this.setState({loading: true})
      this.sqlverify(() => { // 验证成功
        this.setState({
          activeKey: val,
          loading: false
        })
      }, () => {             // 验证失败
        this.setState({
          loading: false
        })
      }, activeKey)
    }
  }
 
  // 自定义脚本修改
  scriptsChange = (scripts) => {
    return new Promise((resolve, reject) => {
      this.sqlverify(resolve, reject, 'verify', scripts)
    })
  }
 
  // 自定义脚本更新
  scriptsUpdate = (scripts) => {
    this.setState({scripts})
  }
 
  render() {
    const { config, menu, dict, permFuncField } = this.props
    const { loading, activeKey, setting, defaultSql, columns, scripts } = this.state
 
    return (
      <div className="model-table-setting-form-box" id="model-setting-form-body">
        {loading && <Spin size="large" />}
        <Tabs activeKey={activeKey} className="verify-card-box" onChange={this.changeTab}>
          <TabPane tab="数据源" key="setting">
            <DataSource
              type={config.Template === 'CommonTable' ? 'main' : ''}
              menu={menu}
              dict={dict}
              columns={columns}
              setting={setting}
              scripts={scripts}
              permFuncField={permFuncField}
              wrappedComponentRef={(inst) => this.settingForm = inst}
            />
          </TabPane>
          <TabPane tab="自定义脚本" key="scripts">
            <CustomScript
              dict={dict}
              setting={setting}
              scripts={scripts}
              defaultSql={defaultSql}
              searches={this.props.search}
              scriptsChange={this.scriptsChange}
              scriptsUpdate={this.scriptsUpdate}
              wrappedComponentRef={(inst) => this.scriptsForm = inst}
            />
          </TabPane>
        </Tabs>
      </div>
    )
  }
}
 
export default Form.create()(SettingForm)