king
2024-08-20 58826d6f4eab9f8c9acf9fa8696f60039c645cfe
src/templates/sharecomponent/settingcomponent/settingform/index.jsx
@@ -1,372 +1,198 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { fromJS } from 'immutable'
import { Form, Row, Col, Input, Radio, Select, Tooltip, Icon, notification, InputNumber, Modal, Table, Popconfirm, Typography, Button } from 'antd'
import moment from 'moment'
import { Form, notification, Modal, Spin, Tabs, Typography, Popconfirm, Button } from 'antd'
import { CheckCircleOutlined, StopOutlined, SwapOutlined, DeleteOutlined, BorderOutlined } from '@ant-design/icons'
import Api from '@/api'
import Utils from '@/utils/utils.js'
import { formatSearch, joinMainSearchkey } from '@/utils/utils-custom.js'
import SettingUtils from './utils.jsx'
import CustomScript from './customscript'
import CodeMirror from '@/templates/zshare/codemirror'
import asyncComponent from '@/utils/asyncComponent'
import DataSource from './datasource'
import MinView from '@/assets/img/minview.png'
import './index.scss'
const { TextArea } = Input
const { confirm } = Modal
const { TabPane } = Tabs
const { Paragraph } = Typography
const CodeMirror = asyncComponent(() => import('@/templates/zshare/codemirror'))
const CustomScript = asyncComponent(() => import('@/templates/zshare/customscript'))
class SettingForm extends Component {
  static propTpyes = {
    type: PropTypes.string,      // 菜单类型
    dict: PropTypes.object,      // 字典项
    menu: PropTypes.object,      // 菜单信息
    config: PropTypes.object,    // 页面配置信息
    formlist: PropTypes.array,   // 表单信息
    inputSubmit: PropTypes.any   // 回车提交事件
    menu: PropTypes.object,         // 菜单信息
    config: PropTypes.object,       // 页面配置信息
    search: PropTypes.array,        // 搜索条件
    updRecord: PropTypes.func
  }
  state = {
    formlist: [],
    btnloading: false,
    search: '',
    activeKey: 'setting',
    searches: [],
    arr_field: '',
    regoptions: [],
    setting: null,
    view: 'normal',
    systemScripts: [{
      name: '默认sql',
      value: ''
    }],
    scriptsColumns: [
      {
        title: 'SQL',
        dataIndex: 'sql',
        width: '70%',
        render: (text) => (
          <Paragraph copyable ellipsis={{ rows: 5, expandable: true }}>{text}</Paragraph>
        )
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: '10%',
        render: (text, record) => record.status === 'false' ?
          (
            <div>
              {this.props.dict['header.form.status.forbidden']}
              <Icon style={{marginLeft: '5px'}} type="stop" theme="twoTone" twoToneColor="#ff4d4f" />
            </div>
          ) :
          (
            <div>
              {this.props.dict['header.form.status.open']}
              <Icon style={{marginLeft: '5px'}} type="check-circle" theme="twoTone" twoToneColor="#52c41a" />
            </div>
          )
      },
      {
        title: '操作',
        align: 'center',
        width: '20%',
        dataIndex: 'operation',
        render: (text, record) =>
          (<div>
            <span className="operation-btn" title={this.props.dict['model.edit']} onClick={() => this.handleEdit(record)} style={{color: '#1890ff'}}><Icon type="edit" /></span>
            <span className="operation-btn" title={this.props.dict['header.form.up']} onClick={() => this.handleUpDown(record, 'up')} style={{color: '#1890ff'}}><Icon type="arrow-up" /></span>
            <span className="operation-btn" title={this.props.dict['header.form.down']} onClick={() => this.handleUpDown(record, 'down')} style={{color: '#ff4d4f'}}><Icon type="arrow-down" /></span>
            <span className="operation-btn" title={this.props.dict['header.form.status.change']} onClick={() => this.handleStatus(record)} style={{color: '#8E44AD'}}><Icon type="swap" /></span>
            <Popconfirm
              title={this.props.dict['header.form.query.delete']}
              okText={this.props.dict['model.confirm']}
              cancelText={this.props.dict['model.cancel']}
              onConfirm={() => this.handleDelete(record)
            }>
              <span className="operation-btn" style={{color: '#ff4d4f'}}><Icon type="delete" /></span>
            </Popconfirm>
          </div>)
      }
    ]
    defaultSql: '',
    visible: false,
    script: null,
    scriptValue: '',
    status: {}
  }
  UNSAFE_componentWillMount() {
    const { config } = this.props
    const { config, search } = this.props
    let _formlist = fromJS(this.props.formlist).toJS()
    let interType = 'inner'
    let _setting = fromJS(config.setting).toJS()
    let _scripts = _setting.scripts || []
    _formlist.forEach(item => {
      if (item.key === 'interType') {
        interType = item.initVal
      }
    })
    let _setting = fromJS(this.props.config.setting).toJS()
    _setting.scripts = _setting.scripts || []
    _setting.default = _setting.default || 'true'
    delete _setting.subtabs
    // 搜索条件
    let allSearch = Utils.initMainSearch(config.search)
    allSearch = Utils.getAllSearchOptions(allSearch)
    _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)
      }
    })
    arr_field = arr_field.join(',')
    let _search = this.formatSearch(config.search)
    _search = Utils.joinMainSearchkey(_search)
    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
        }
      })
    }
    _search = _search.replace(/@\$@/ig, '')
    _search = _search ? 'where ' + _search : ''
    let status = fromJS(_setting).toJS()
    // if (window.GLOB.funcs && window.GLOB.funcs.length > 0) {
    //   window.GLOB.funcs.forEach(m => {
    //     let reg = new RegExp(`\\/\\*\\$ex@${m.func_code}-begin\\*\\/[\\s\\S]+\\/\\*@ex\\$-end\\*\\/`, 'ig')
    //     _scripts.forEach(item => {
    //       item.sql = item.sql.replace(reg, `$ex@${m.func_code}@ex$`)
    //     })
    //     if (_setting.dataresource) {
    //       _setting.dataresource = _setting.dataresource.replace(reg, `$ex@${m.func_code}@ex$`)
    //     }
    //   })
    // }
    this.setState({
      setting: _setting,
      search: _search,
      arr_field: arr_field,
      regoptions: allSearch,
      formlist: _formlist.map(item => {
        if (interType === 'inner' && ['sysInterface', 'interface', 'outerFunc'].includes(item.key)) {
          item.hidden = true
        } else if (interType === 'outer' && ['innerFunc', 'dataresource', 'queryType', 'default'].includes(item.key)) {
          item.hidden = true
        }
        return item
      })
      searches: formatSearch(search),
      arr_field: arr_field.join(','),
      columns: columns,
      scripts: _scripts,
      status
    })
  }
  componentDidMount () {
    this.getsysScript()
    this.props.updRecord(this.state.status)
  }
  getsysScript = () => {
    let _scriptSql = `Select distinct func+Remark as funcname,longparam, s.Sort from  s_custom_script s inner join (select OpenID from sapp where ID=@Appkey@) p on s.openid = case when s.appkey='' then s.openid else p.OpenID end order by s.Sort`
  handleConfirm = (trigger) => {
    const { activeKey, setting, scripts } = this.state
    _scriptSql = Utils.formatOptions(_scriptSql)
    let _sParam = {
      func: 'sPC_Get_SelectedList',
      LText: _scriptSql,
      obj_name: 'data',
      arr_field: 'funcname,longparam'
    }
    _sParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    _sParam.secretkey = Utils.encrypt(_sParam.LText, _sParam.timestamp)
    _sParam.open_key = Utils.encrypt(_sParam.secretkey, _sParam.timestamp, true) // 云端数据验证
    Api.getSystemConfig(_sParam).then(res => {
      if (res.status) {
        let _scripts = res.data.map(item => {
          let _item = {
            name: item.funcname,
            value: Utils.formatOptions(item.longparam, true)
          }
          return _item
        })
        this.setState({
          systemScripts: [...this.state.systemScripts, ..._scripts]
        })
      } else {
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      }
    })
  }
  handleConfirm = (otype) => {
    const { menu, type } = this.props
    const { view, setting } = this.state
    // 表单提交时检查输入值是否正确
    if (view !== 'custom') {
      return new Promise((resolve, reject) => {
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
            if (type === 'main') {
              values.actionfixed = values.actionfixed === 'true'
              values.columnfixed = values.columnfixed === 'true'
            }
            values = {...setting, ...values}
            // 数据源前端验证
            if (values.interType === 'inner' && !values.innerFunc && values.default !== 'false' && !values.dataresource) {
              notification.warning({
                top: 92,
                message: '请填写内部函数或数据源!',
                duration: 5
              })
              reject()
              return
            } else if (values.interType === 'inner' && !values.innerFunc && values.default !== 'false' && values.dataresource) {
              let _quot = values.dataresource.match(/'{1}/g)
              let _lparen = values.dataresource.match(/\({1}/g)
              let _rparen = values.dataresource.match(/\){1}/g)
              _quot = _quot ? _quot.length : 0
              _lparen = _lparen ? _lparen.length : 0
              _rparen = _rparen ? _rparen.length : 0
              if (_quot % 2 !== 0) {
                notification.warning({
                  top: 92,
                  message: '数据源中\'必须成对出现',
                  duration: 5
                })
                reject()
                return
              } else if (_lparen !== _rparen) {
                notification.warning({
                  top: 92,
                  message: '数据源中()必须成对出现',
                  duration: 5
                })
                reject()
                return
              } else if (/--/ig.test(values.dataresource)) {
                notification.warning({
                  top: 92,
                  message: '数据源中,不可出现字符 -- ,注释请用 /*内容*/',
                  duration: 5
                })
                reject()
                return
              }
              let error = Utils.verifySql(values.dataresource)
              if (error) {
                notification.warning({
                  top: 92,
                  message: '数据源中不可使用' + error,
                  duration: 5
                })
                reject()
                return
              }
            }
            // 数据源保存
            if (
              values.interType === 'inner' && !values.innerFunc &&
              values.default !== 'false' &&
              /[^\s]+\s+[^\s]+/ig.test(values.dataresource) &&
              this.props.config.setting.dataresource !== values.dataresource
            ) {
              let param = {
                func: 's_DataSrc_Save',
                LText: values.dataresource,
                MenuID: menu.MenuID
              }
              param.LText = Utils.formatOptions(param.LText)
              param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
              param.secretkey = Utils.encrypt(param.LText, param.timestamp)
              Api.getLocalConfig(param)
            }
            if (otype === 'change') {
              this.setState({
                setting: values,
              }, () => {
                resolve()
              })
            } else {
              values.customScript = this.getCustomScript(values)
              this.sqlverify(values, resolve, reject)
            }
          } else {
            reject(err)
          }
        })
      })
    } else {
      let _setting = fromJS(this.state.setting).toJS()
      _setting.customScript = this.getCustomScript(_setting)
      let _this = this
      return new Promise((resolve, reject) => {
        if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql')) {
          confirm({
            content: `存在未保存项,确定提交吗?`,
            okText: this.props.dict['model.confirm'],
            cancelText: this.props.dict['model.cancel'],
            onOk() {
              _this.sqlverify(_setting, resolve, reject)
            },
            onCancel() {
              reject()
            }
          })
        } else {
          this.sqlverify(_setting, resolve, reject)
        }
      })
    }
  }
  getCustomScript = (setting) => {
    let _customScript = ''
    if (setting.scripts && setting.scripts.length > 0) {
      setting.scripts.forEach(item => {
        if (item.status === 'false') return
        _customScript += `
          ${item.sql}
        `
      })
    }
    if (_customScript) {
      _customScript = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000) select @ErrorCode='',@retmsg =''
        ${_customScript}
      `
    }
    return _customScript
  }
  sqlverify = (_setting, _resolve, _reject, isChange = false) => {
    const { arr_field, regoptions, search } = this.state
    if (!isChange && _setting.interType === 'inner' && !_setting.innerFunc && _setting.default === 'false' && !_setting.customScript) {
    if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql') && !/^\s+$/.test(this.scriptsForm.props.form.getFieldValue('sql'))) {
      notification.warning({
        top: 92,
        message: '不执行默认sql时,请添加自定义脚本!',
        message: '存在未保存脚本,请点击确定保存,或点击取消放弃修改!',
        duration: 5
      })
      _reject()
      return Promise.reject()
    }
    if (trigger) {
      this.setState({loading: true})
    }
    // 表单提交时检查输入值是否正确
    if (activeKey === 'setting') {
      return new Promise((resolve, reject) => {
        this.settingForm.handleConfirm().then(res => {
          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 if (activeKey === 'scripts') {
      return new Promise((resolve, reject) => {
        this.sqlverify(() => {
          this.setState({loading: false})
          resolve({...setting, scripts})
        }, () => {
          this.setState({loading: false})
          reject()
        }, 'submit')
      })
    } else {
      this.setState({loading: false})
      return new Promise((resolve) => {
        resolve({...setting, scripts})
      })
    }
  }
  sqlverify = (_resolve, _reject, type, uscripts) => {
    const { config } = this.props
    const { setting, scripts, arr_field, searches } = this.state
    if (setting.interType !== 'system') { // 不使用系统接口时,不需要sql验证
      _resolve()
      return
    }
    if (_setting.interType === 'inner' && !_setting.innerFunc && _setting.default !== 'false') {
      let param = {
        func: 's_debug_sql',
        LText: SettingUtils.getDebugSql(_setting, arr_field, regoptions, search)
    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 r = SettingUtils.getDebugSql(setting, _scripts, arr_field, searches, config.urlFields)
      if (r.errors) {
        notification.warning({
          top: 92,
          message: r.errors,
          duration: 5
        })
      }
      param.LText = Utils.formatOptions(param.LText)
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      
      Api.getLocalConfig(param).then(result => {
        if (result.status) {
          _resolve(_setting)
      Api.sDebug(r.sql).then(result => {
        if (result.status || result.ErrCode === '-2') {
          _resolve()
        } else {
          _reject()
          Modal.error({
@@ -374,532 +200,267 @@
          })
        }
      })
    } else {
      _resolve(_setting)
    }
  }
  selectChange = (key, val) => {
    if (key === 'primaryKey' && val) {
      this.props.form.setFieldsValue({
        order: `${val} desc`
  // 标签切换
  changeTab = (val) => {
    const { activeKey, searches, arr_field } = this.state
    if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql') && !/^\s+$/.test(this.scriptsForm.props.form.getFieldValue('sql'))) {
      notification.warning({
        top: 92,
        message: '存在未保存的脚本!',
        duration: 5
      })
    }
  }
  onRadioChange = (e, key) => {
    let value = e.target.value
    let _formlist = fromJS(this.state.formlist).toJS()
    if (activeKey === 'setting') {
      let _defaultSql = ''
      this.settingForm.handleConfirm().then(res => {
        if (res.dataresource) {
          let _dataresource = res.dataresource
    if (key === 'interType') {
      this.setState({
        formlist: _formlist.map(item => {
          item.hidden = false
          let _search = joinMainSearchkey(searches)
          if (value === 'inner' && ['sysInterface', 'interface', 'outerFunc'].includes(item.key)) {
            item.initVal = this.props.form.getFieldValue(item.key)
            item.hidden = true
          } else if (value === 'outer' && ['innerFunc', 'dataresource', 'queryType', 'default'].includes(item.key)) {
            item.initVal = this.props.form.getFieldValue(item.key)
            item.hidden = true
          if (/\s/.test(_dataresource)) {
            _dataresource = '(' + _dataresource + ') tb'
          }
          return item
        })
      })
    } else if (key === 'sysInterface') {
      if (value === 'true') {
        this.props.form.setFieldsValue({
          interface: window.GLOB.mainSystemApi || ''
        })
      }
      this.setState({
        formlist: _formlist.map(item => {
          if (item.key === 'interface') {
            item.readonly = value === 'true'
          }
          return item
        })
      })
    }
  }
  /**
   * @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 = '='
          _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`
        }
        
        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
  }
  changeView = () => {
    const { view, arr_field, regoptions, search } = this.state
    let _this = this
    if (view === 'normal') {
      this.handleConfirm('change').then(() => {
        const { setting } = this.state
        if (setting.interType !== 'inner' || (setting.interType === 'inner' && setting.innerFunc)) {
          notification.warning({
            top: 92,
            message: '使用外部接口或内部接口的自定义函数,不可添加自定义设置!',
            duration: 5
          })
          return
        }
        let _search = search
        let _dataresource = setting.dataresource
        if (/\s/.test(_dataresource)) {
          _dataresource = '(' + _dataresource + ') tb'
        }
        if (setting.queryType === 'statistics') { // 统计数据源,内容替换
          // 正则替换
          let _regoptions = regoptions.map(item => {
            return {
              reg: new RegExp('@' + item.key + '@', 'ig'),
              value: `'${item.value}'`
            }
          })
          _regoptions.forEach(item => {
            _dataresource = _dataresource.replace(item.reg, item.value)
          })
          _search = ''
        }
        let LText = `select ${setting.laypage !== 'false' ?  'top @pageSize@' : ''} ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by @orderBy@) as rows from ${_dataresource} ${_search}) tmptable ${setting.laypage !== 'false' ?  'where rows > (@pageSize@ * (@pageIndex@ - 1))' : ''} order by tmptable.rows`
        let _scripts = fromJS(this.state.systemScripts).toJS()
        _scripts[0].value = LText
        if (setting.default === 'false') {
          this.setState({
            view: 'custom',
            btnloading: false,
            systemScripts: _scripts
          })
          this.scrolltop()
        } else {
          this.setState({
            btnloading: true
          })
          new Promise((resolve, reject) => {
            this.sqlverify(setting, resolve, reject, true)
          }).then(() => {
        this.setState({
          setting: res,
          defaultSql: _defaultSql
        }, () => {
          this.setState({loading: true})
          this.sqlverify(() => { // 验证成功
            this.setState({
              view: 'custom',
              btnloading: false,
              systemScripts: _scripts
              activeKey: val,
              loading: false
            })
            this.scrolltop()
          }, () => {
          }, () => {             // 验证失败
            this.setState({
              btnloading: false
              activeKey: val,
              loading: false
            })
          })
        }
          }, activeKey)
        })
      })
    } else if (activeKey === 'scripts') {
      this.setState({loading: true})
      this.sqlverify(() => { // 验证成功
        this.setState({
          activeKey: val,
          loading: false
        })
      }, () => {             // 验证失败
        this.setState({
          activeKey: val,
          loading: false
        })
      }, activeKey)
    } else {
      let _loading = false
      if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql')) {
        _loading = true
      }
      if (_loading) {
        confirm({
          content: `存在未保存项,确定切换吗?`,
          okText: this.props.dict['model.confirm'],
          cancelText: this.props.dict['model.cancel'],
          onOk() {
            _this.setState({
              view: 'normal'
            })
            _this.scrolltop()
          },
          onCancel() {}
        })
      } else {
        _this.setState({
          view: 'normal'
        })
        _this.scrolltop()
      }
      this.setState({
        activeKey: val
      })
    }
  }
  handleSubmit = (e) => {
    e.preventDefault()
    if (this.props.inputSubmit) {
      this.props.inputSubmit()
    }
  }
  getFields(formlist) {
    const { getFieldDecorator } = this.props.form
    const fields = []
    formlist.forEach((item, index) => {
      if (item.hidden || item.forbid) return
      if (item.type === 'text') { // 文本搜索
        let rules = item.rules || []
        fields.push(
          <Col span={12} key={index}>
            <Form.Item label={item.tooltip ?
              <Tooltip placement="topLeft" title={item.tooltip}>
                <Icon type="question-circle" />
                {item.label}
              </Tooltip> : item.label
            }>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal || '',
                rules: [
                  {
                    required: !!item.required,
                    message: this.props.dict['form.required.input'] + item.label + '!'
                  },
                  ...rules
                ]
              })(<Input placeholder={item.placeholder || ''} autoComplete="off" disabled={item.readonly} onPressEnter={this.handleSubmit} />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'number') {
        fields.push(
          <Col span={12} key={index}>
            <Form.Item label={item.tooltip ?
              <Tooltip placement="topLeft" title={item.tooltip}>
                <Icon type="question-circle" />
                {item.label}
              </Tooltip> : item.label
            }>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal || 6,
                rules: [
                  {
                    required: item.required,
                    message: this.props.dict['form.required.input'] + item.label + '!'
                  }
                ]
              })(<InputNumber min={item.min} max={item.max} precision={0} />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'select') { // 下拉搜索
        fields.push(
          <Col span={12} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal || '',
                rules: [
                  {
                    required: !!item.required,
                    message: this.props.dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <Select
                  showSearch
                  filterOption={(input, option) => {
                    return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                      option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }}
                  onChange={(value) => {this.selectChange(item.key, value)}}
                  getPopupContainer={() => document.getElementById('model-table-setting-form')}
                >
                  {item.options.map((option, i) =>
                    <Select.Option id={i} key={i} value={option.value}>
                      {option.text}
                    </Select.Option>
                  )}
                </Select>
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'radio') {
        fields.push(
          <Col span={12} key={index}>
            <Form.Item label={item.tooltip ?
              <Tooltip placement="topLeft" title={item.tooltip}>
                <Icon type="question-circle" />
                {item.label}
              </Tooltip> : item.label
            }>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal,
                rules: [
                  {
                    required: !!item.required,
                    message: this.props.dict['form.required.select'] + item.label + '!'
                  }
                ]
              })(
                <Radio.Group onChange={(e) => {this.onRadioChange(e, item.key)}}>
                  {
                    item.options.map((option, i) => {
                      return (
                        <Radio key={i} value={option.value}>{option.text}</Radio>
                      )
                    })
                  }
                </Radio.Group>,
              )}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'datasource') {
        fields.push(
          <Col span={24} key={index} style={{paddingLeft: '7px'}}>
            <Form.Item className="text-area" labelCol={{xs: { span: 24 }, sm: { span: 4 }}} wrapperCol={ {xs: { span: 24 }, sm: { span: 20 }} } help={item.help} label={
              <Tooltip placement="topLeft" title={item.tooltip}>
                <Icon type="question-circle" />
                {item.label}
              </Tooltip>
            }>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal
              })(<CodeMirror />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'textarea') {
        fields.push(
          <Col span={20} offset={4} key={index}>
            <Form.Item className="text-area">
              {getFieldDecorator(item.key, {
                initialValue: item.initVal,
                rules: [
                  {
                    required: !!item.required,
                    message: this.props.dict['form.required.input'] + item.label + '!'
                  }
                ]
              })(<TextArea rows={4} />)}
            </Form.Item>
          </Col>
        )
      } else if (item.type === 'multiselect') { // 多选
        fields.push(
          <Col span={12} key={index}>
            <Form.Item label={item.label}>
              {getFieldDecorator(item.key, {
                initialValue: item.initVal || []
              })(
                <Select
                  showSearch
                  mode="multiple"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {item.options.map((option, i) =>
                    <Select.Option id={i} key={i} value={option.value}>{option.text}</Select.Option>
                  )}
                </Select>
              )}
            </Form.Item>
          </Col>
        )
      }
  // 自定义脚本修改
  scriptsChange = (scripts) => {
    return new Promise((resolve, reject) => {
      this.sqlverify(resolve, reject, 'verify', scripts)
    })
    return fields
  }
  handleEdit = (record) => {
    this.scriptsForm.edit(record)
  triggerConfirm = () => {
    const { script, scriptValue, scripts } = this.state
    let _scripts = fromJS(scripts).toJS()
    this.scrolltop()
  }
  scrolltop = () => {
    let node = document.getElementById('model-table-setting-form-box').parentNode
    if (node && node.scrollTop) {
      let inter = Math.ceil(node.scrollTop / 10)
      let timer = setInterval(() => {
        if (node.scrollTop - inter > 0) {
          node.scrollTop = node.scrollTop - inter
        } else {
          node.scrollTop = 0
          clearInterval(timer)
        }
      }, 10)
    }
  }
  handleUpDown = (record, direction) => {
    let scripts = fromJS(this.state.setting.scripts).toJS()
    let index = 0
    scripts = scripts.filter((item, i) => {
      if (item.uuid === record.uuid) {
        index = i
      }
      return item.uuid !== record.uuid
    })
    if ((index === 0 && direction === 'up') || (index === scripts.length && direction === 'down')) {
    if (!scriptValue) {
      notification.warning({
        top: 92,
        message: '请输入sql!',
        duration: 5
      })
      return
    }
    if (direction === 'up') {
      scripts.splice(index - 1, 0, record)
    } else {
      scripts.splice(index + 1, 0, record)
    }
    this.setState({
      setting: {...this.state.setting, scripts: scripts}
    })
  }
  handleStatus = (record) => {
    let scripts = fromJS(this.state.setting.scripts).toJS()
    record.status = record.status === 'false' ? 'true' : 'false'
    scripts = scripts.map(item => {
      if (item.uuid === record.uuid) {
        return record
      } else {
        return item
      }
    })
    this.setState({
      setting: {...this.state.setting, scripts: scripts}
    })
  }
  handleDelete = (record) => {
    let scripts = fromJS(this.state.setting.scripts).toJS()
    scripts = scripts.filter(item => item.uuid !== record.uuid)
    this.setState({ setting: {...this.state.setting, scripts: scripts} })
  }
  scriptsChange = (values) => {
    let scripts = fromJS(this.state.setting.scripts).toJS()
    if (values.uuid) {
      scripts = scripts.map(item => {
        if (item.uuid === values.uuid) {
          return values
        } else {
          return item
    if (script) {
      _scripts = _scripts.map(item => {
        if (script.uuid === item.uuid) {
          item.sql = scriptValue
        }
        return item
      })
    } else {
      values.uuid = Utils.getuuid()
      scripts.push(values)
      let _script = {
        uuid: Utils.getuuid(),
        sql: scriptValue,
        $index: _scripts.length + 1,
        status: 'true'
      }
      _scripts.push(_script)
    }
    this.setState({
      setting: {...this.state.setting, scripts: scripts}
    })
    this.setState({loading: true})
    this.sqlverify(() => {this.setState({scripts: _scripts, script: null, scriptValue: '', loading: false})}, () => {this.setState({loading: false})}, 'verify', _scripts)
  }
  // 自定义脚本更新
  scriptsUpdate = (scripts) => {
    this.setState({scripts})
  }
  handleDelete = (item) => {
    const { script, scripts } = this.state
    if (script && script.uuid === item.uuid) {
      this.setState({script: null})
    }
    this.setState({scripts: scripts.filter(cell => cell.uuid !== item.uuid)})
  }
  handleStatus = (item) => {
    item.status = item.status === 'false' ? 'true' : 'false'
    this.setState({scripts: this.state.scripts.map(cell => {
      if (cell.uuid === item.uuid) {
        return item
      }
      return cell
    })})
  }
  updateStatus = (status) => {
    let _status = {...this.state.status, ...status}
    this.setState({status: _status})
    this.props.updRecord(_status)
  }
  render() {
    const { config, type } = this.props
    const { formlist, view, setting, scriptsColumns, systemScripts, arr_field, regoptions, search, btnloading } = this.state
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const { config, menu } = this.props
    const { loading, activeKey, setting, defaultSql, columns, scripts, status, visible, script, scriptValue } = this.state
    return (
      <div className="model-table-setting-form-box" id="model-table-setting-form-box">
        {view ==='custom' ? <div>
          <Icon className="setting-custom-back" onClick={this.changeView} type="arrow-left" />
          <CustomScript
            type={type}
            setting={setting}
            swhere={search}
            arr_field={arr_field}
            regoptions={regoptions}
            dict={this.props.dict}
            searches={config.search}
            systemScripts={systemScripts}
            scriptsChange={this.scriptsChange}
            wrappedComponentRef={(inst) => this.scriptsForm = inst}
          />
          <Table
            bordered
            rowKey="uuid"
            className="custom-table"
            dataSource={setting.scripts}
            columns={scriptsColumns}
            pagination={false}
          />
        </div> : null }
        <Form {...formItemLayout} className="model-table-setting-form" id="model-table-setting-form">
          {view !=='custom' ? <Row gutter={24}>{this.getFields(formlist)}</Row> : null}
          <Row gutter={24}>
            {view !=='custom' ? <Button onClick={this.changeView} className="to-custom-script" loading={btnloading}>自定义设置<Icon style={{marginLeft: 5}} type="right" /></Button> : null}
            {view ==='custom' ? <span onClick={this.changeView} style={{float: 'left', color: '#1890ff', marginLeft: 12, marginTop: 15, cursor: 'pointer'}}><Icon style={{marginRight: 5}} type="left" />基础设置</span> : null}
          </Row>
        </Form>
      <div className="model-table-setting-form-box">
        {loading && <Spin size="large" />}
        <Tabs activeKey={activeKey} onChange={this.changeTab}>
          <TabPane tab="数据源" key="setting">
            <DataSource
              menu={menu}
              config={config}
              columns={columns}
              setting={setting}
              scripts={scripts}
              updateStatus={this.updateStatus}
              wrappedComponentRef={(inst) => this.settingForm = inst}
            />
          </TabPane>
          <TabPane tab={
            <span>
              自定义脚本
              {scripts.length ? <span className="count-tip">{scripts.length}</span> : null}
            </span>
          } disabled={status.interType !== 'system'} key="scripts" id="mk-setting-scripts">
            {scripts.length ? <BorderOutlined className="full-scripts" onClick={() => {
              if (this.scriptsForm && (this.scriptsForm.state.editItem || (this.scriptsForm.props.form.getFieldValue('sql') && !/^\s+$/.test(this.scriptsForm.props.form.getFieldValue('sql'))))) {
                notification.warning({
                  top: 92,
                  message: '请保存自定义脚本!',
                  duration: 5
                })
                return
              }
              this.setState({visible: true, script: null, scriptValue: ''})
            }}/> : null}
            <CustomScript
              setting={setting}
              scripts={scripts}
              defaultSql={defaultSql}
              urlFields={config.urlFields}
              searches={this.state.searches}
              scriptsChange={this.scriptsChange}
              scriptsUpdate={this.scriptsUpdate}
              wrappedComponentRef={(inst) => this.scriptsForm = inst}
            />
          </TabPane>
        </Tabs>
        <Modal
          wrapClassName="model-custom-table-scripts-modal"
          title="自定义脚本"
          visible={visible}
          width={'95vw'}
          maskClosable={false}
          destroyOnClose
        >
          <img className="unfull-scripts" src={MinView} onClick={() => this.setState({visible: false, script: null})} alt=""/>
          <div className="script-table-wrap">
            {scripts.map(item => {
              let title = item.sql.match(/^\s*\/\*.+\*\//)
              title = title && title[0] ? title[0] : ''
              let _text = title ? item.sql.replace(title, '') : item.sql
              if (item.status === 'false') {
                return (
                  <div className="script-item" key={item.uuid}>
                    <div style={{cursor: 'not-allowed'}}>
                      {title ? <div style={{color: '#a50', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{title}</div> : null}
                      <Paragraph copyable={{ text: item.sql }} ellipsis={{ rows: 4 }}>{_text}</Paragraph>
                      <div>
                        <span style={{color: '#ff4d4f', marginLeft: '20px'}}>
                          禁用
                          <StopOutlined style={{marginLeft: '5px'}} />
                        </span>
                      </div>
                    </div>
                    <div style={{height: '24px'}}></div>
                  </div>
                )
              } else {
                return (
                  <div className={'script-item ' + (script && script.uuid === item.uuid ? 'active' : '') } key={item.uuid}>
                    <div style={{cursor: 'pointer'}} onClick={() => {
                      this.setState({script: item, scriptValue: item.sql})
                    }}>
                      {title ? <div style={{color: '#a50', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{title}</div> : null}
                      <Paragraph copyable={{ text: item.sql }} ellipsis={{ rows: 4 }}>{_text}</Paragraph>
                      <div>
                        <span style={{color: '#26C281', marginLeft: '20px'}}>
                          启用
                          <CheckCircleOutlined style={{marginLeft: '5px'}}/>
                        </span>
                      </div>
                    </div>
                    <div style={{textAlign: 'right'}}>
                      <span className="operation-btn" onClick={() => this.handleStatus(item)} style={{color: '#8E44AD'}}><SwapOutlined /></span>
                      <Popconfirm
                        overlayClassName="popover-confirm"
                        title="确定删除吗?"
                        onConfirm={() => this.handleDelete(item)
                      }>
                        <span className="operation-btn" style={{color: '#ff4d4f'}}><DeleteOutlined /></span>
                      </Popconfirm>
                    </div>
                  </div>
                )
              }
            })}
          </div>
          <div className="script-button">
            <Button onClick={this.triggerConfirm} loading={loading} className="mk-green" style={{marginBottom: 15, marginLeft: 40}}>
              {script ? '保存' : '添加'}
            </Button>
            <Button onClick={() => {this.setState({script: null, scriptValue: ''})}} style={{marginBottom: 15, marginLeft: 10}}>
              取消
            </Button>
          </div>
          <CodeMirror value={scriptValue} onChange={(val) => {this.setState({scriptValue: val})}}></CodeMirror>
        </Modal>
      </div>
    )
  }