king
2023-08-17 c7aece35a62b6e91fd98a625bf0e53f64bfbd18d
src/tabviews/zshare/topSearch/index.jsx
@@ -1,93 +1,153 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { fromJS } from 'immutable'
import { Form, Row, Col, Input, Button, Select, DatePicker, notification } from 'antd'
import { Form, Row, Col, Button, notification, Modal, Drawer } from 'antd'
import { CloseOutlined, DownOutlined } from '@ant-design/icons'
import moment from 'moment'
import md5 from 'md5'
import Api from '@/api'
import options from '@/store/options.js'
import DateGroup from '@/tabviews/zshare/dategroup'
import asyncComponent from '@/utils/asyncComponent'
import asyncSpinComponent from '@/utils/asyncSpinComponent'
import Utils from '@/utils/utils.js'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import MKEmitter from '@/utils/events.js'
import MKInput from './mkInput'
import './index.scss'
const { MonthPicker, WeekPicker, RangePicker } = DatePicker
const MutilForm = asyncSpinComponent(() => import('./advanceform'))
const MKCheckCard = asyncComponent(() => import('./mkCheckCard'))
const MKCheck = asyncComponent(() => import('@/tabviews/zshare/mutilform/mkCheck'))
const MKSwitch = asyncComponent(() => import('@/tabviews/zshare/mutilform/mkSwitch'))
const MKRadio = asyncComponent(() => import('./mkRadio'))
const MKSelect = asyncComponent(() => import('./mkSelect'))
const DateGroup = asyncComponent(() => import('./dategroup'))
const MKDatePicker = asyncComponent(() => import('./mkDatePicker'))
class MainSearch extends Component {
  static propTpyes = {
    BID: PropTypes.any,          // 父级Id,用于查询下拉选择项
    menuType: PropTypes.any,     // 菜单权限,是否为HS
    searchlist: PropTypes.array, // 搜索条件列表
    config: PropTypes.object,    // 组件配置信息(自定义页面)
    refreshdata: PropTypes.func  // 刷新数据
    config: PropTypes.object,    // 组件配置信息
  }
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    oriId: Utils.getuuid(),  // 搜索表单Id
    formId: '',              // 搜索表单Id
    match: null,             // 搜索条件匹配规则
    style: null,             // 搜索条件类型
    label: null,             // 提示文字
    required: null,          // 是否必填
    searchlist: null,        // 搜索项
    groups: null,            // 组合搜索项
    float: '',               // 浮动
    showButton: true,        // 是否显示搜索按钮
    searchStyle: null        // 搜索条件样式
    setting: {},
    advanceValues: [],       // 高级搜索条件保存值
    visible: false,
    hasReqFields: false
  }
  record = {}
  sign = ''
  UNSAFE_componentWillMount () {
    const { config, menuType, searchlist } = this.props
    const { config } = this.props
    let _searchlist = []
    let match = {}
    let label = {}
    let style = {}
    let required = {}
    let _list = []
    let fieldMap = new Map()
    let mainItems = []  // 云端或单点数据
    let localItems = [] // 本地数据
    let deForms = []    // 测试系统,单个请求
    let float = ''
    let showButton = true
    let searchStyle = null
    let formId = Utils.getuuid()
    let advanceValues = []
    let linkFields = {}
    let record = {}
    let forbid = false // header中不设置高级搜索
    let _setting = {showAdv: false, show: false, style: null}
    if (config.wrap) {
      _setting.show = config.wrap.show !== 'false'
      _setting.advanceType = config.wrap.advanceType || 'modal'
      _setting.advWidth = config.wrap.advanceWidth || 1000
      _setting.placement = config.wrap.drawerPlacement || 'right'
      _setting.ratio = config.wrap.searchRatio || 6
      _setting.labelwidth = config.wrap.searchLwidth !== undefined ? config.wrap.searchLwidth : 33.3
      _setting.labelCol = {style: {width: _setting.labelwidth + '%'}}
      _setting.wrapperCol = {style: {width: (100 - _setting.labelwidth) + '%'}}
      _setting.borderRadius = config.wrap.borderRadius
      _setting.resetContrl = config.wrap.resetContrl || 'init'
    }
    if (config.type === 'search') {
      _setting.float = config.wrap.float || 'left'
      _setting.style = config.style
    } else if (config.type === 'table') {
      _setting.float = 'left'
    } else {
      _setting.float = 'right'
      _setting.show = false
      forbid = true
    }
    if (searchlist) {
      _searchlist = fromJS(searchlist).toJS()
    } else if (config) {
      _searchlist = fromJS(config.search).toJS()
      if (config.type === 'search' && config.subtype === 'mainsearch') {
        float = config.wrap.float
        showButton = config.wrap.float === 'left' && config.wrap.show === 'true'
        searchStyle = config.style
    if (_setting.advanceType === 'drawer' && _setting.advWidth) {
      if (_setting.placement === 'top' || _setting.placement === 'bottom') {
        _setting.advHeight = _setting.advWidth > 100 ? _setting.advWidth + 'px' : _setting.advWidth + 'vh'
        _setting.advWidth = '100vw'
      } else {
        formId = ''
        showButton = false
        float = 'right'
        _setting.advWidth = _setting.advWidth > 100 ? _setting.advWidth + 'px' : _setting.advWidth + 'vw'
      }
    } else if (_setting.advanceType === 'modal' && _setting.advWidth) {
      if (_setting.advWidth < 100) {
        _setting.advWidth = _setting.advWidth + 'vw'
      } else {
        _setting.advWidth = _setting.advWidth + 'px'
      }
    }
    _searchlist = fromJS(config.search).toJS()
    _searchlist.forEach(item => {
      if (item.linkField) {
        linkFields[item.linkField] = linkFields[item.linkField] || []
        linkFields[item.linkField].push({field: item.field, uuid: item.uuid})
      }
      let labelwidth = item.labelwidth || 33.3
      if (item.labelShow === 'false') {
        labelwidth = 0
      }
      item.labelCol = {style: {width: labelwidth + '%'}}
      item.wrapperCol = {style: {width: (100 - labelwidth) + '%'}}
      if (fieldMap.has(item.field)) {
        item.field = item.field + '@tail@'
      }
      fieldMap.set(item.field, item)
      match[item.field] = item.match
      label[item.field] = item.label
      style[item.field] = item.type
      required[item.field] = item.required === 'true'
      if (item.advanced && !forbid) {
        _setting.showAdv = true
      } else {
        item.advanced = false
      }
      if (['select', 'link', 'multiselect'].includes(item.type)) {
        if (item.setAll === 'true' && item.type !== 'multiselect') {
      if (item.advanced && item.initval) {
        let val = item.initval
        if (item.precision === 'hour') {
          if (/,/ig.test(val)) {
            val = val.split(',').map(m => m + ':00').join(',')
          } else {
            val = val + ':00'
          }
        }
        if (['text', 'date', 'datemonth', 'dateweek', 'daterange'].includes(item.type)) {
          advanceValues.push({field: item.field, type: item.type, label: item.label, value: val})
        }
      }
      if (item.type === 'group') {
        record[item.field] = item.initType
        record[item.datefield] = item.initval
      } else {
        record[item.field] = item.initval
      }
      if (['select', 'link', 'multiselect', 'checkcard', 'radio'].includes(item.type)) {
        item.options = item.options || []
        item.options = item.options.filter(op => !op.Hide)
        if (item.setAll === 'true' && ['select', 'link'].includes(item.type)) {
          item.options.unshift({
            key: Utils.getuuid(),
            Value: '',
            Text: this.state.dict['main.all']
            Text: '全部',
            ParentID: ''
          })
        }
@@ -95,34 +155,45 @@
        if (item.resourceType === '1' && item.dataSource) {
          let _option = Utils.getSelectQueryOptions(item)
          if (window.GLOB.debugger === true) {
            console.info(_option.sql)
          }
          // 测试系统单个请求
          if (menuType !== 'HS' && options.sysType === 'local' && !window.GLOB.systemType) {
          if (!window.GLOB.mkHS && window.GLOB.sysType === 'local' && !window.GLOB.systemType) {
            deForms.push({
              ...item,
              arr_field: _option.field,
              data_sql: Utils.formatOptions(_option.sql)
            })
          } else { // 合并请求,区分本地及系统
            // 外联数据库替换
            if (window.GLOB.externalDatabase !== null) {
              _option.sql = _option.sql.replace(/@db@/ig, window.GLOB.externalDatabase)
            }
            if (item.database === 'sso') {
              mainItems.push(`select '${item.field}' as obj_name,'${_option.field}' as arr_field,'${window.btoa(window.encodeURIComponent(_option.sql))}' as LText`)
              mainItems.push(`select '${item.field}' as obj_name,'${_option.field}' as arr_field,'${window.btoa(window.encodeURIComponent(_option.sql.replace(/%/ig, ' mpercent ')))}' as LText`)
            } else {
              localItems.push(`select '${item.field}' as obj_name,'${_option.field}' as arr_field,'${window.btoa(window.encodeURIComponent(_option.sql))}' as LText`)
              localItems.push(`select '${item.field}' as obj_name,'${_option.field}' as arr_field,'${window.btoa(window.encodeURIComponent(_option.sql.replace(/%/ig, ' mpercent ')))}' as LText`)
            }
          }
        }
        item.oriOptions = fromJS(item.options).toJS()
        if (item.type === 'checkcard' && item.multiple === 'dropdown' && item.resourceType === '0') {
          this.resetCheckcard(item)
        }
      }
      _list.push(item)
      fieldMap.set(item.field, item)
    })
    let _groups = []
    _list = _list.map(item => {
      if (item.type === 'link') {
    this.record = record
    let _list = _searchlist.map(item => {
      if (item.hidden) return item
      if (linkFields[item.field] && (item.type === 'select' || item.type === 'link' || (item.type === 'checkcard' && item.multiple !== 'true'))) {
        item.linkFields = linkFields[item.field]
      }
      if (item.linkField) {
        let supItem = fieldMap.get(item.linkField)
        
        if (!supItem) {
@@ -131,47 +202,66 @@
            message: '未查询到搜索条件《' + item.label + '》关联字段!',
            duration: 5
          })
          item.supInitVal = ''
          item.type = 'select'
        } else {
          item.supInitVal = supItem.initval
          item.options = item.oriOptions.filter(option => option.ParentID === supItem.initval || option.Value === '')
        }
      } else if (item.type === 'group' && item.Hide !== 'true') {
        _groups.push(fromJS(item).toJS())
      }
      return item
    })
    this.setState({
      match,
      label,
      style,
      float,
      formId,
      required,
      showButton,
      searchStyle,
      searchlist: _list,
      groups: _groups
      setting: _setting,
      hasReqFields: config.$s_req,
      advanceValues,
      searchlist: _list
    }, () => {
      if (menuType !== 'HS' && options.sysType === 'local' && !window.GLOB.systemType) {
      if (!window.GLOB.mkHS && window.GLOB.sysType === 'local' && window.GLOB.systemType !== 'production') {
        this.improveSimpleSearch(deForms)
      } else {
      } else if (mainItems.length > 0 || localItems.length > 0) {
        this.improveSearch(mainItems, localItems)
      }
    })
  }
  resetCheckcard = (item) => {
    let pid = item.resourceType === '0' ? 'pid' : item.parentField
    let _options = []
    let _others = []
    item.oriOptions.forEach(op => {
      if (op[pid] === item.mark) {
        _options.push(op)
      } else {
        _others.push(op)
      }
    })
    _options = _options.map(op => {
      op.children = []
      _others = _others.filter(cell => {
        if (cell[pid] === op.$value) {
          op.children.push(cell)
          return false
        }
        return true
      })
      op.subIds = op.children.map(cell => cell.$value)
      return op
    })
    item.oriOptions = _options
    item.options = _options
  }
  // 查询下拉菜单
  improveSearch = (mainItems, localItems) => {
    const { menuType, BID } = this.props
    const { BID } = this.props
    let deffers = []
    if (menuType !== 'HS' && window.GLOB.systemType !== 'production') {
      localItems = [...localItems, ...mainItems]
      mainItems = []
    }
    // 本地请求
    let param = {
@@ -191,7 +281,7 @@
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      if (menuType === 'HS') { // 云端数据验证
      if (window.GLOB.mkHS) { // 云端数据验证
        param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
      }
@@ -229,10 +319,10 @@
      mainparam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      mainparam.secretkey = Utils.encrypt(mainparam.LText, mainparam.timestamp)
      if (menuType === 'HS') { // 云端数据验证
      if (window.GLOB.mkHS) { // 云端数据验证
        mainparam.open_key = Utils.encryptOpenKey(mainparam.secretkey, mainparam.timestamp)
        if (options.cloudServiceApi) {
          mainparam.rduri = options.cloudServiceApi
        if (window.GLOB.cloudServiceApi) {
          mainparam.rduri = window.GLOB.cloudServiceApi
          mainparam.userid = sessionStorage.getItem('CloudUserID') || ''
          mainparam.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
        }
@@ -264,42 +354,7 @@
      delete result.message
      delete result.status
      let _searchlist = this.state.searchlist.map(item => {
        if (['select', 'link', 'multiselect'].includes(item.type) && result[item.field] && result[item.field].length > 0) {
          let options = result[item.field].map(cell => {
            let _item = {
              key: Utils.getuuid(),
              Value: cell[item.valueField],
              Text: cell[item.valueText]
            }
            if (item.type === 'link') {
              _item.ParentID = cell[item.linkField]
            }
            return _item
          })
          item.oriOptions = [...item.oriOptions, ...options]
        }
        return item
      })
      this.setState({
        searchlist: _searchlist.map(item => {
          if (item.type === 'link') {
            if (item.supInitVal) {
              item.options = item.oriOptions.filter(option => option.ParentID === item.supInitVal || option.Value === '')
            } else {
              item.options = item.oriOptions
            }
          } else if (item.type === 'select' || item.type === 'multiselect') {
            item.options = item.oriOptions
          }
          return item
        })
      })
      this.resetSearch(result)
    })
  }
@@ -307,7 +362,7 @@
  improveSimpleSearch = (deForms) => {
    if (deForms.length === 0) return
    let deffers = deForms.map(item => {
    let deffers = deForms.map((item, index) => {
      let param = {
        func: 'sPC_Get_SelectedList',
        LText: item.data_sql,
@@ -322,18 +377,24 @@
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      if (item.database === 'sso' && window.GLOB.mainSystemApi) {
        param.rduri = window.GLOB.mainSystemApi
      }
      return (
        new Promise(resolve => {
          Api.getSystemCacheConfig(param).then(res => {
            if (!res.status) {
              notification.warning({
                top: 92,
                message: res.message,
                duration: 5
              })
            }
            resolve(res)
          })
          setTimeout(() => {
            Api.getSystemCacheConfig(param).then(res => {
              if (!res.status) {
                notification.warning({
                  top: 92,
                  message: res.message,
                  duration: 5
                })
              }
              resolve(res)
            })
          }, index * 30)
        })
      )
    })
@@ -350,299 +411,195 @@
      delete result.message
      delete result.status
      let _searchlist = this.state.searchlist.map(item => {
        if (['select', 'link', 'multiselect'].includes(item.type) && result[item.field] && result[item.field].length > 0) {
          let options = result[item.field].map(cell => {
            let _item = {
              key: Utils.getuuid(),
              Value: cell[item.valueField],
              Text: cell[item.valueText]
            }
      this.resetSearch(result)
    })
  }
            if (item.type === 'link') {
              _item.ParentID = cell[item.linkField]
            }
            return _item
          })
          item.oriOptions = [...item.oriOptions, ...options]
        }
        return item
      })
      this.setState({
        searchlist: _searchlist.map(item => {
          if (item.type === 'link') {
            if (item.supInitVal) {
              item.options = item.oriOptions.filter(option => option.ParentID === item.supInitVal || option.Value === '')
            } else {
              item.options = item.oriOptions
            }
          } else if (item.type === 'select' || item.type === 'multiselect') {
            item.options = item.oriOptions
  resetSearch = (result) => {
    let _searchlist = fromJS(this.state.searchlist).toJS().map(item => {
      if (['select', 'link', 'multiselect', 'checkcard', 'radio'].includes(item.type) && result[item.field] && result[item.field].length > 0) {
        let options = []
        let map = new Map()
        let all = false
        result[item.field].forEach(cell => {
          let _item = {
            key: Utils.getuuid(),
            ParentID: ''
          }
          return item
          if (item.linkField) {
            _item.ParentID = cell[item.linkField]
          }
          if (item.type !== 'checkcard') {
            _item.Value = cell[item.valueField]
            _item.Text = cell[item.valueText] + ''
            if (map.has(_item.ParentID + _item.Value)) return
            if (!_item.Text) {
              if (!all) {
                _item.Text = '全部'
                all = true
              } else {
                return
              }
            }
            map.set(_item.ParentID + _item.Value, 0)
          } else {
            _item.$value = cell[item.cardValField]
            _item = {..._item, ...cell}
            if (item.urlField) {
              _item.$url = cell[item.urlField] || ''
            } else if (item.colorField) {
              _item.$color = cell[item.colorField] || ''
            }
            if (map.has(_item.ParentID + _item.$value)) return
            map.set(_item.ParentID + _item.$value, 0)
          }
          options.push(_item)
        })
      })
    })
  }
  resetform = (formlist, supfields, index, fieldsvalue) => {
    index++
    let subfields = []
        item.oriOptions = [...item.oriOptions, ...options]
    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 || option.Value === '')
          item.initval = item.options[0] ? item.options[0].Value : ''
          if (this.props.form.getFieldValue(item.field) !== undefined) {
            fieldsvalue[item.field] = item.initval
          }
          subfields.push(item)
        if (item.type === 'checkcard' && item.multiple === 'dropdown') {
          this.resetCheckcard(item)
        }
        return item
      })
    })
    if (subfields.length === 0 || index > 6) {
      return formlist
    } else {
      return this.resetform(formlist, subfields, index, fieldsvalue)
    }
  }
  selectChange = (_field, value) => {
    let formlist = fromJS(this.state.searchlist).toJS()
    let subfields = []
    let fieldsvalue = {}
    formlist = formlist.map(item => {
      if (item.type === 'link' && item.linkField === _field.field) {
        item.options = item.oriOptions.filter(option => option.ParentID === value || option.Value === '')
        item.initval = item.options[0] ? item.options[0].Value : ''
        if (this.props.form.getFieldValue(item.field) !== undefined) {
          fieldsvalue[item.field] = item.initval
        }
        subfields.push(item)
      }
      if (item.linkField) {
        if (item.supInitVal) {
          item.options = item.oriOptions.filter(option => option.ParentID === item.supInitVal || option.Value === '')
        } else {
          item.options = item.oriOptions
        }
      } else if (item.oriOptions) {
        item.options = item.oriOptions
      }
      return item
    })
    if (subfields.length === 0) {
      this.searchChange()
      return
    }
    formlist = this.resetform(formlist, subfields, 0, fieldsvalue)
    if (Object.keys(fieldsvalue).length > 0) {
      this.props.form.setFieldsValue(fieldsvalue)
    }
    this.setState({
      searchlist: formlist
    }, () => {
      this.searchChange()
      searchlist: _searchlist
    })
  }
  recordChange = (val, defer, item) => {
    this.record[item.field] = val
    if (defer) return
    if (item.linkFields) {
      setTimeout(() => {
        this.handleSubmit()
      }, 1000)
    } else {
      setTimeout(() => {
        this.handleSubmit()
      }, 10)
    }
  }
  dateGroupChange = (val, type, item) => {
    this.record[item.datefield] = val
    this.record[item.field] = type
    this.handleSubmit()
  }
  cardChange = (val, item) => {
    this.record[item.field] = val
    if (!item.linkFields) {
      setTimeout(() => {
        this.handleSubmit()
      }, 10)
    }
  }
  getFields() {
    const { getFieldDecorator } = this.props.form
    const { dict, showButton, formId } = this.state
    const { visible, setting } = this.state
    const fields = []
    this.state.searchlist.forEach((item, index) => {
      if (item.Hide === 'true') return
      if (item.type === 'text') { // 文本搜索
        fields.push(
          <Col span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: item.initval,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.input'] + item.label + '!'
                  }
                ]
              })(<Input placeholder={item.labelShow === 'false' ? item.label : ''} autoComplete="off" onPressEnter={this.handleSearch} />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'select') { // 下拉搜索
        fields.push(
          <Col span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: item.initval,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <Select
                  showSearch
                  onChange={(value) => {this.selectChange(item, value)}}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  getPopupContainer={() => formId ? document.getElementById(formId) : document.body}
                >
                  {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={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: _initval,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <Select
                  showSearch
                  mode="multiple"
                  onChange={this.searchChange}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  getPopupContainer={() => formId ? document.getElementById(formId) : document.body}
                >
                  {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={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: item.initval ? moment().subtract(item.initval, 'days') : null,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <DatePicker onChange={this.searchChange} getCalendarContainer={() => formId ? document.getElementById(formId) : document.body} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'datemonth') {
        fields.push(
          <Col span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: item.initval ? moment().subtract(item.initval, 'month') : null,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <MonthPicker onChange={this.searchChange} getCalendarContainer={() => formId ? document.getElementById(formId) : document.body} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'dateweek') {
        fields.push(
          <Col span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field, {
                initialValue: item.initval ? moment().subtract(item.initval * 7, 'days') : null,
                rules: [
                  {
                    required: item.required === 'true',
                    message: dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <WeekPicker onChange={this.searchChange} getCalendarContainer={() => formId ? document.getElementById(formId) : document.body} />
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'daterange') {
        let _defaultValue = [null, null]
      if (item.hidden || (item.advanced && (setting.advanceType !== 'pulldown' || !visible))) return
        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]
          }
      const _rules = [
        {
          required: item.required,
          message: item.label + '不可为空!'
        }
      ]
        fields.push(
          <Col className="daterange" span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''}>
              {getFieldDecorator(item.field,
                {
                  initialValue: _defaultValue,
                  rules: [
                    {
                      required: item.required === 'true',
                      message: dict['form.required.select'] + item.label + '!'
                    }
                  ]
                })(
                <RangePicker
                  placeholder={['开始日期', '结束日期']}
                  renderExtraFooter={() => 'extra footer'}
                  onChange={this.searchChange}
                  getCalendarContainer={() => formId ? document.getElementById(formId) : document.body}
                />
              )}
            </Form.Item>
          </Col>
        )
      let content = null
      let field = item.field
      if (item.type === 'text') {
        content = (<MKInput config={item} onInputSubmit={this.handleSubmit} />)
      } else if (item.type === 'select' || item.type === 'link' || item.type === 'multiselect') {
        content = (<MKSelect config={item} onChange={(val, defer) => this.recordChange(val, defer, item)} />)
      } else if (item.type === 'date' || item.type === 'datemonth' || item.type === 'dateweek' || item.type === 'daterange') {
        content = (<MKDatePicker config={item} onChange={(val) => this.recordChange(val, false, item)} />)
      } else if (item.type === 'group') {
        field = item.datefield
        content = <DateGroup position={index} config={item} onChange={(val, type) => this.dateGroupChange(val, type, item)} />
      } else if (item.type === 'checkcard') {
        content = <MKCheckCard config={item} onChange={(val) => this.cardChange(val, item)} />
      } else if (item.type === 'radio') {
        content = <MKRadio config={item} onChange={(val) => this.recordChange(val, false, item)} />
      } else if (item.type === 'check') {
        content = <MKCheck config={item} onChange={(val) => this.recordChange(val, false, item)} />
      } else if (item.type === 'switch') {
        content = <MKSwitch config={item} onChange={(val) => this.recordChange(val, false, item)} />
      }
      if (content) {
        fields.push(
          <Col span={item.ratio || 6} key={index}>
            <Form.Item label={item.labelShow !== 'false' ? item.label : ''} className={item.required === 'true' ? 'group-required' : ''}>
              <DateGroup ref={item.uuid} position={index} card={item} onGroupChange={this.searchChange} />
          <Col className="mk-search-col" span={item.ratio || 6} key={index}>
            <Form.Item
              label={item.labelShow !== 'false' ? item.label : ''}
              labelCol={item.labelCol}
              wrapperCol={item.wrapperCol}
            >
              {getFieldDecorator(field, {
                initialValue: item.initval,
                rules: _rules
              })(content)}
            </Form.Item>
          </Col>
        )
      }
    })
    if (showButton) {
    if (setting.show || setting.showAdv) {
      let style = {}
      if (setting.borderRadius) {
        style.borderRadius = setting.borderRadius
      }
      fields.push(
        <Col span={6} style={{ whiteSpace: 'nowrap' }} className="search-button" key="actions">
          <Form.Item label={' '} colon={false} style={{ minHeight: '40px' }}>
            <Button type="primary" onClick={this.handleSearch}>
              {dict['main.search']}
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
              {dict['main.reset']}
            </Button>
        <Col span={setting.ratio} style={{ whiteSpace: 'nowrap' }} className="mk-search-col search-button" key="actions">
          <Form.Item
            label={' '}
            colon={false}
            labelCol={setting.labelCol}
            wrapperCol={setting.wrapperCol}
          >
            {setting.show ? <Button style={style} type="primary" onClick={this.handleSubmit}>
              搜索
            </Button> : null}
            {setting.show ? <Button style={{ marginLeft: 8, ...style }} onClick={this.handleReset}>
              重置
            </Button> : null}
            {setting.showAdv ? <Button className={visible ? 'visible' : ''} type="link" onClick={this.handleAdvance}>
              高级{setting.advanceType === 'pulldown' ? <DownOutlined /> : null}
            </Button> : null}
          </Form.Item>
        </Col>
      )
@@ -651,60 +608,92 @@
    return fields
  }
  addHideFieldValue = (values) => {
    const { searchlist } = this.state
    let hideValue = {}
    searchlist.forEach(item => {
      if (item.Hide === 'true') {
        let value = ''
  handleAdvance = () => {
    const { setting, visible } = this.state
        if (item.type === 'multiselect') { // 下拉多选
          value = item.initval ? item.initval.split(',').filter(Boolean) : []
        } else if (item.type === 'date') { // 时间搜索
          value = item.initval ? moment().subtract(item.initval, 'days') : ''
        } else if (item.type === 'datemonth') {
          value = item.initval ? moment().subtract(item.initval, 'month') : ''
        } else if (item.type === 'dateweek') {
          value = item.initval ? moment().subtract(item.initval * 7, 'days') : ''
        } else if (item.type === 'daterange') {
          if (item.initval) {
            try {
              let _initval = JSON.parse(item.initval)
              value = [moment().subtract(_initval[0], 'days'), moment().subtract(_initval[1], 'days')]
            } catch {
              value = ''
    if (setting.advanceType !== 'pulldown' && visible) {
      return
    }
    this.setState({visible: !visible})
    if (setting.advanceType === 'pulldown') {
      if (visible) {
        let advanceValues = []
        this.state.searchlist.forEach(item => {
          if (!item.advanced) return
          let val = this.record[item.field]
          if (val || val === 0) {
            if (item.precision === 'hour') {
              if (/,/ig.test(val)) {
                val = val.split(',').map(m => m + ':00').join(',')
              } else {
                val = val + ':00'
              }
            }
            if (['text', 'date', 'datemonth', 'dateweek', 'daterange'].includes(item.type)) {
              advanceValues.push({field: item.field, type: item.type, label: item.label, value: val})
            }
          }
        } else if (item.type !== 'group') {
          value = item.initval
        }
        hideValue[item.field] = value
        })
        this.setState({advanceValues})
      } else {
        let list = this.state.searchlist.map(item => {
          if (!item.advanced) return item
          item.initval = this.record[item.field]
          return item
        })
        this.setState({searchlist: list})
      }
    })
    return {...hideValue, ...values}
    }
  }
  handleSearch = (e) => {
    // 回车或点击搜索
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values = this.addHideFieldValue(values)
        let searches = this.getFieldsValues(values)
        this.props.refreshdata(searches)
      }
    })
  }
  searchChange = () => {
  handleSubmit = () => {
    this.setState({}, () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          values = this.addHideFieldValue(values)
          let searches = this.getFieldsValues(values)
        if (err) return
        let { searches, error } = this.getFieldsValues(values)
        if (error) {
          notification.warning({
            top: 92,
            message: error,
            duration: 3
          })
          return
        } else if (this.state.hasReqFields) {
          let requireFields = searches.filter(item => item.required && item.value === '')
          if (requireFields.length > 0) {
            let labels = requireFields.map(item => item.label)
            labels = Array.from(new Set(labels))
            notification.warning({
              top: 92,
              message: '请输入' + labels.join('、') + ' !',
              duration: 3
            })
            return
          }
        }
        let sign = md5(JSON.stringify(searches))
        if (sign === this.sign) return
        this.sign = sign
        setTimeout(() => {
          this.sign = ''
        }, 2000)
        if (this.props.refreshdata) {
          this.props.refreshdata(searches)
        } else {
          window.GLOB.SearchBox.set(this.props.config.$searchId, searches)
          MKEmitter.emit('searchRefresh', this.props.config.$searchId)
        }
      })
    })
@@ -714,87 +703,168 @@
   * @description 搜索条件重置
   */
  handleReset = () => {
    const { groups } = this.state
    const { setting } = this.state
    if (groups.length > 0) {
      groups.forEach(item => {
        this.refs[item.uuid].reset()
      })
    }
    let record = {}
    let advanceValues = []
    let searchlist = this.state.searchlist.map(item => {
      item.initval = item.oriInitval
      if (setting.resetContrl === 'clear' && ['text', 'date', 'datemonth', 'dateweek', 'daterange'].includes(item.type)) {
        item.initval = ''
      }
      if (item.type === 'group') {
        record[item.datefield] = item.initval
        record[item.field] = item.initType
      } else {
        record[item.field] = item.initval
      }
      if (item.advanced && item.initval) {
        let val = item.initval
        if (item.precision === 'hour') {
          if (/,/ig.test(val)) {
            val = val.split(',').map(m => m + ':00').join(',')
          } else {
            val = val + ':00'
          }
        }
        if (['text', 'date', 'datemonth', 'dateweek', 'daterange'].includes(item.type)) {
          advanceValues.push({field: item.field, type: item.type, label: item.label, value: val})
        }
      }
      return item
    })
    this.setState({searchlist}, () => {
      this.props.form.resetFields()
      this.props.form.validateFields((err, values) => {
        if (!err) {
          // 异步获取更新后的时间组
          this.setState({}, () => {
            values = this.addHideFieldValue(values)
            let searches = this.getFieldsValues(values)
            this.props.refreshdata(searches)
          })
        }
    this.record = record
    this.setState({searchlist: [], advanceValues}, () => {
      this.setState({searchlist}, () => {
        this.handleSubmit()
      })
    })
  }
  getFieldsValues = (values) => {
    const { groups } = this.state
  getFieldsValues = (vals) => {
    const { searchlist } = this.state
    let values = {...this.record, ...vals}
    this.record = values
    // 获取搜索条件值
    let search = []
    Object.keys(values).forEach(key => {
      let _value = ''
      if (this.state.style[key] === 'daterange') {
        if (values[key].length > 0 && values[key][0] && values[key][1]) {
          _value = [moment(values[key][0]).format('YYYY-MM-DD'), moment(values[key][1]).format('YYYY-MM-DD')]
        }
      } else if (this.state.style[key] === 'dateweek') {
        if (values[key]) {
          _value = [moment(values[key]).startOf('week').format('YYYY-MM-DD'), moment(values[key]).endOf('week').format('YYYY-MM-DD')]
        }
      } else if (this.state.style[key] === 'date') {
        if (values[key]) {
          _value = moment(values[key]).format('YYYY-MM-DD')
        }
      } else if (this.state.style[key] === 'datemonth') {
        if (values[key]) {
          _value = moment(values[key]).format('YYYY-MM')
        }
      } else if (this.state.style[key] === 'multiselect') {
        _value = values[key] || []
    let error = null
    searchlist.forEach(item => {
      if (item.type === 'group') {
        search.push({
          type: 'daterange',
          key: item.datefield,
          value: values[item.datefield] || '',
          label: item.label,
          match: 'between',
          required: item.required,
          precision: 'day',
          forbid: item.$forbid
        }, {
          type: 'group',
          key: item.field,
          value: values[item.field] || '',
          label: item.label,
          match: '=',
          forbid: true,
          required: item.required
        })
      } else {
        _value = (values[key] || values[key] === 0) ? values[key] : ''
        let type = item.type
        let val = values[item.field] !== undefined ? values[item.field] : ''
        _value = _value.replace(/(^\s*|\s*$)/ig, '')
        if (type === 'multiselect' || (type === 'checkcard' && item.multiple === 'true')) {
          type = 'multi'
        } else if (type === 'text' && !error) {
          if (/'/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用英文状态的单引号。`
          } else if (/--/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用 -- 。`
          } else if (/(^|\s)select\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字select。`
          } else if (/\sfrom(\s|\()/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字from。`
          } else if (/(^|\s)insert\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字insert。`
          } else if (/(^|\s)delete\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字delete。`
          } else if (/(^|\s)update\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字update。`
          } else if (/(^|\s)where\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字where。`
          } else if (/(^|\s)drop\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字drop。`
          } else if (/(^|\s)exec\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字exec。`
          } else if (/(^|\s)truncate\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字truncate。`
          } else if (/(^|\s)while\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字while。`
          } else if (/(^|\s)for\s/ig.test(val)) {
            error = `搜索条件${item.label}中,不可使用关键字for。`
          }
        }
        if (typeof(val) === 'string') {
          val = val.replace(/(^\s*|\s*$)/ig, '')
        }
        search.push({
          type: type,
          key: item.field.replace(/@tail@$/, ''),
          value: val,
          label: item.label,
          match: item.match,
          required: item.required,
          precision: item.precision || 'day',
          forbid: item.$forbid
        })
      }
      search.push({
        type: this.state.style[key],
        key: key.replace(/@tail@$/, ''),
        value: _value,
        label: this.state.label[key],
        match: this.state.match[key],
        required: this.state.required[key]
      })
    })
    if (groups.length > 0) {
      groups.forEach(item => {
        let items = this.refs[item.uuid].getSearchItems()
        search.push(...items)
      })
    }
    return {searches: search, error}
  }
    return search
  handleOk = (values) => {
    this.record = {...this.record, ...values}
    let advanceValues = []
    this.state.searchlist.forEach(item => {
      if (!item.advanced) return
      let val = this.record[item.field]
      if (val || val === 0) {
        if (item.precision === 'hour') {
          if (/,/ig.test(val)) {
            val = val.split(',').map(m => m + ':00').join(',')
          } else {
            val = val + ':00'
          }
        }
        if (['text', 'date', 'datemonth', 'dateweek', 'daterange'].includes(item.type)) {
          advanceValues.push({field: item.field, type: item.type, label: item.label, value: val})
        }
      }
    })
    this.setState({advanceValues, visible: false})
    this.handleSubmit()
  }
  closeAdvanceForm = (cell) => {
    this.record[cell.field] = ''
    this.setState({advanceValues: this.state.advanceValues.filter(item => item.field !== cell.field)})
    this.handleSubmit()
  }
  render() {
    const { float, searchStyle } = this.state
    const { visible, searchlist, advanceValues, setting } = this.state
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
@@ -807,9 +877,57 @@
    }
    return (
      <Form {...formItemLayout} className={`top-search ${float}`} style={searchStyle} id={this.state.formId || this.state.oriId}>
        <Row gutter={24}>{this.getFields()}</Row>
      </Form>
      <>
        <Form {...formItemLayout} className={`mk-search-wrap mk-float-${setting.float}`} style={setting.style}>
          <Row gutter={24}>{this.getFields()}</Row>
          {advanceValues.length && (setting.advanceType !== 'pulldown' || (setting.advanceType === 'pulldown' && !visible)) ? <Row gutter={24}>
            <div className="advanced-list">
              {advanceValues.map((item, index) => {
                return (
                  <div key={index}>
                    <span>{item.label}: </span>
                    <span className="advance-value">{item.value}</span>
                    <CloseOutlined onClick={() => this.closeAdvanceForm(item)} />
                  </div>)
              })}
            </div>
          </Row> : null}
        </Form>
        {setting.advanceType === 'modal' ? <Modal
          title="高级搜索"
          maskClosable={false}
          visible={visible}
          width={setting.advWidth}
          closable={false}
          footer={null}
          destroyOnClose
        >
          <MutilForm
            searchlist={searchlist}
            record={this.record}
            advanceSubmit={this.handleOk}
            handleClose={() => this.setState({visible: false})}
          />
        </Modal> : null}
        {setting.advanceType === 'drawer' ? <Drawer
          title="高级搜索"
          className="mk-search-drawer"
          width={setting.advWidth}
          height={setting.advHeight}
          maskClosable={false}
          onClose={() => this.setState({visible: false})}
          visible={visible}
          placement={setting.placement}
          destroyOnClose
        >
          <MutilForm
            searchlist={searchlist}
            record={this.record}
            advanceSubmit={this.handleOk}
            handleClose={() => this.setState({visible: false})}
          />
        </Drawer> : null}
      </>
    )
  }
}