king
2020-02-15 c76e56d9cc6f8f5e93aaf355b269ec8cac8c6b95
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
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { Form, Row, Col, Input, Button, Select, DatePicker, notification } from 'antd'
import moment from 'moment'
import Utils from '@/utils/utils.js'
import './index.scss'
 
const {MonthPicker, WeekPicker, RangePicker} = DatePicker
 
class MainSearch extends Component {
  static propTpyes = {
    searchlist: PropTypes.array, // 搜索条件列表
    dict: PropTypes.object // 字典项
  }
 
  state = {
    match: null,            // 搜索条件匹配规则
    style: null,
    searchlist: null,
    formId: Utils.getuuid()
  }
 
  UNSAFE_componentWillMount () {
    let searchlist = JSON.parse(JSON.stringify(this.props.searchlist))
    let match = {}
    let style = {}
    let _list = []
    let fieldMap = new Map()
 
    searchlist.forEach(item => {
      if (fieldMap.has(item.field)) {
        item.field = item.field + '@tail@'
      }
      fieldMap.set(item.field, true)
 
      match[item.field] = item.match
      style[item.field] = item.type
 
      if (item.type === 'select' || item.type === 'link') {
        item.oriOptions = JSON.parse(JSON.stringify(item.options))
      }
 
      _list.push(item)
    })
 
    let error = false
 
    _list = _list.map(item => {
      if (item.type === 'link') {
        let supItem = _list.filter(form => form.field === item.linkField)[0]
        
        if (!supItem) {
          error = true
        } else {
          item.options = item.oriOptions.filter(option => option.parentId === supItem.initval)
        }
      }
 
      return item
    })
 
    if (error) {
      notification.warning({
        top: 92,
        message: '关联菜单设置错误!',
        duration: 10
      })
    }
 
    this.setState({
      match: match,
      style: style,
      searchlist: _list
    })
  }
 
  UNSAFE_componentWillReceiveProps(nextProps) {
    let searchlist = JSON.parse(JSON.stringify(nextProps.searchlist))
    let _list = []
    let fieldMap = new Map()
 
    searchlist.forEach(item => {
      if (fieldMap.has(item.field)) {
        item.field = item.field + '@tail@'
      }
      fieldMap.set(item.field, true)
 
      if (item.type === 'select' || item.type === 'link') {
        item.oriOptions = JSON.parse(JSON.stringify(item.options))
      }
 
      _list.push(item)
    })
 
    _list = _list.map(item => {
      if (item.type === 'link') {
        let supItem = _list.filter(form => form.field === item.linkField)[0]
        
        if (supItem) {
          item.options = item.oriOptions.filter(option => option.parentId === supItem.initval)
        }
      }
 
      return item
    })
 
    this.setState({
      searchlist: _list
    })
  }
 
  resetform = (formlist, supfields, index) => {
    index++
    let subfields = []
 
    supfields.forEach(supfield => {
      formlist = formlist.map(item => {
        if (item.type === 'link' && item.linkField === supfield.field) {
          item.options = item.oriOptions.filter(option => option.parentId === supfield.initval)
          item.initval = item.options[0] ? item.options[0].Value : ''
          item.hiden = true
  
          subfields.push(item)
        }
        return item
      })
    })
 
    if (subfields.length === 0 || index > 6) {
      return formlist
    } else {
      return this.resetform(formlist, subfields, index)
    }
  }
 
  selectChange = (_field, value) => {
    let formlist = JSON.parse(JSON.stringify(this.state.searchlist))
 
    let subfields = []
    formlist = formlist.map(item => {
      if (item.type === 'link' && item.linkField === _field.field) {
        item.options = item.oriOptions.filter(option => option.parentId === value)
        item.initval = item.options[0] ? item.options[0].Value : ''
        item.hiden = true
 
        subfields.push(item)
      }
      return item
    })
 
    if (subfields.length === 0) {
      this.searchChange()
      return
    }
 
    formlist = this.resetform(formlist, subfields, 0)
 
    this.setState({
      searchlist: formlist
    }, () => {
      this.setState({
        searchlist: formlist.map(item => {
          item.hiden = false
          return item
        })
      }, () => {
        this.searchChange()
      })
    })
  }
 
  getFields() {
    const { getFieldDecorator } = this.props.form
    const fields = []
 
    this.state.searchlist.forEach((item, index) => {
      if (item.hidden) return
 
      if (item.type === 'text') { // 文本搜索
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: item.initval })(<Input placeholder="" autoComplete="off" />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'select') { // 下拉搜索
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: item.initval })(
                <Select
                  showSearch
                  onChange={(value) => {this.selectChange(item, value)}}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  getPopupContainer={() => document.getElementById(this.state.formId)}
                >
                  {item.options.map((option, i) =>
                    <Select.Option id={`${i}`} title={option.Text} key={`${i}`} value={option.Value}>{option.Text}</Select.Option>
                  )}
                </Select>
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'multiselect') { // 下拉多选
        let _initval = item.initval ? item.initval.split(',').filter(Boolean) : []
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: _initval })(
                <Select
                  showSearch
                  mode="multiple"
                  // onChange={(value) => {this.selectChange(item, value)}}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  getPopupContainer={() => document.getElementById(this.state.formId)}
                >
                  {item.options.map((option, i) =>
                    <Select.Option id={`${i}`} title={option.Text} key={`${i}`} value={option.Value}>{option.Text}</Select.Option>
                  )}
                </Select>
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'date') { // 时间搜索
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: item.initval ? moment().subtract(item.initval, 'days') : null })(
                <DatePicker onChange={this.searchChange} getCalendarContainer={() => document.getElementById(this.state.formId)} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'datemonth') {
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: item.initval ? moment().subtract(item.initval, 'month') : null })(
                <MonthPicker onChange={this.searchChange} getCalendarContainer={() => document.getElementById(this.state.formId)} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'dateweek') {
        fields.push(
          <Col span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field, {initialValue: item.initval ? moment().subtract(item.initval * 7, 'days') : null })(
                <WeekPicker onChange={this.searchChange} getCalendarContainer={() => document.getElementById(this.state.formId)} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'daterange') {
        let _defaultValue = [null, null]
 
        if (item.initval) {
          try {
            let _initval = JSON.parse(item.initval)
            _defaultValue = [moment().subtract(_initval[0], 'days'), moment().subtract(_initval[1], 'days')]
          } catch {
            _defaultValue = [null, null]
          }
        }
 
        fields.push(
          <Col className="daterange" span={6} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.field,
                {
                  initialValue: _defaultValue
                })(
                <RangePicker
                  placeholder={['开始日期', '结束日期']}
                  renderExtraFooter={() => 'extra footer'}
                  onChange={this.searchChange}
                  getCalendarContainer={() => document.getElementById(this.state.formId)}
                />
              )}
            </Form.Item>
          </Col>
        )
      }
    })
 
    if (this.props.searchlist.length >= 4) { // 添加搜索、重置按钮
      fields.push(
        <Col span={this.props.searchlist.length % 4 ? 6 : 24} style={{paddingLeft: '112px', whiteSpace: 'nowrap'}} key="actions">
          <Button type="primary" htmlType="submit">
            {this.props.dict['main.search']}
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
            {this.props.dict['main.reset']}
          </Button>
        </Col>
      )
    } else {
      fields.push(
        <Col span={6} style={{ paddingTop: '4px', whiteSpace: 'nowrap' }} key="actions">
          <Button type="primary" htmlType="submit">
            {this.props.dict['main.search']}
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
            {this.props.dict['main.reset']}
          </Button>
        </Col>
      )
    }
    
    return fields
  }
 
  handleSearch = (e) => {
    // 回车或点击搜索
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      let searches = this.getFieldsValues(values)
      this.props.refreshdata(searches)
    })
  }
 
  searchChange = () => {
    this.setState({}, () => {
      this.props.form.validateFields((err, values) => {
        let searches = this.getFieldsValues(values)
        this.props.refreshdata(searches)
      })
    })
  }
 
  handleReset = () => {
    // 重置
    this.props.form.resetFields()
    this.props.form.validateFields((err, values) => {
      let searches = this.getFieldsValues(values)
      this.props.refreshdata(searches)
    })
  }
 
  getFieldsValues = (values) => {
    // 获取搜索条件值
    let search = []
    Object.keys(values).forEach(key => {
      if (this.state.style[key] === 'daterange') {
        let _value = ''
        if (values[key].length > 0) {
          _value = [moment(values[key][0]).format('YYYY-MM-DD'), moment(values[key][1]).format('YYYY-MM-DD')]
        }
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: _value,
          match: this.state.match[key]
        })
      } else if (this.state.style[key] === 'dateweek') {
        let _value = ''
        if (values[key]) {
          _value = [moment(values[key]).startOf('week').format('YYYY-MM-DD'), moment(values[key]).endOf('week').format('YYYY-MM-DD')]
        }
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: _value,
          match: this.state.match[key]
        })
      } else if (this.state.style[key] === 'date') {
        let _value = ''
        if (values[key]) {
          _value = moment(values[key]).format('YYYY-MM-DD')
        }
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: _value,
          match: this.state.match[key]
        })
      } else if (this.state.style[key] === 'datemonth') {
        let _value = ''
        if (values[key]) {
          _value = moment(values[key]).format('YYYY-MM')
        }
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: _value,
          match: this.state.match[key]
        })
      } else if (this.state.style[key] === 'multiselect') {
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: values[key],
          match: this.state.match[key]
        })
      } else {
        search.push({
          type: this.state.style[key],
          key: key.replace(/@tail@$/, ''),
          value: values[key].replace(/(^\s*|\s*$)/ig, ''),
          match: this.state.match[key]
        })
      }
    })
    return search
  }
 
  render() {
    return (
      <Form className="ant-advanced-search-form top-search" id={this.state.formId} onSubmit={this.handleSearch}>
        <Row gutter={24}>{this.getFields()}</Row>
      </Form>
    )
  }
}
 
export default Form.create()(MainSearch)