king
2020-09-16 c34bcb0a3054bdab29fbaff17e587c19d7b5de28
src/views/menudesign/index.jsx
@@ -4,13 +4,14 @@
import { is, fromJS } from 'immutable'
import moment from 'moment'
import HTML5Backend from 'react-dnd-html5-backend'
import { Icon, notification, Modal, Collapse } from 'antd'
import html2canvas from 'html2canvas'
import { ConfigProvider, notification, Modal, Collapse, Card, Icon, Switch, Button } from 'antd'
import Api from '@/api'
import Utils from '@/utils/utils.js'
import zhCN from '@/locales/zh-CN/mob.js'
import enUS from '@/locales/en-US/mob.js'
import antdEnUS from 'antd/es/locale/en_US'
import antdZhCN from 'antd/es/locale/zh_CN'
import asyncComponent from '@/utils/asyncComponent'
import './index.scss'
@@ -18,23 +19,27 @@
// const { TabPane } = Tabs
const { Panel } = Collapse
const { confirm } = Modal
const _locale = localStorage.getItem('lang') !== 'en-US' ? antdZhCN : antdEnUS
const Header = asyncComponent(() => import('@/menu/header'))
const MenuForm = asyncComponent(() => import('@/menu/menuform'))
const SourceWrap = asyncComponent(() => import('@/menu/modelsource'))
const MenuShell = asyncComponent(() => import('@/menu/menushell'))
// const Controller = asyncComponent(() => import('@/mob/controller'))
const SourceWrap = asyncComponent(() => import('@/mob/modelsource'))
// const DataSource = asyncComponent(() => import('@/mob/datasource'))
const TableComponent = asyncComponent(() => import('@/templates/sharecomponent/tablecomponent'))
class Mobile extends Component {
sessionStorage.setItem('isEditState', 'true')
class MenuDesign extends Component {
  state = {
    dict: localStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    MenuId: this.props.match.params.MenuId,
    tableFields: [],
    activeKey: 'basedata',
    menuloading: false,
    oriConfig: null,
    parentId: '',
    openEdition: '',
    saveIng: false,
    config: null,
    editElem: null
  }
@@ -42,6 +47,10 @@
  UNSAFE_componentWillMount() {
    this.getMenuParam()
    // this.testFunc()
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.state), fromJS(nextState))
  }
  /**
@@ -53,16 +62,17 @@
    }
  }
  reloadTab = () => {
  }
  closeView = () => {
    const { oriConfig, config } = this.state
    const _this = this
    if (!is(fromJS(oriConfig), fromJS(config))) {
      confirm({
        title: '配置已修改,放弃保存吗?',
        content: '',
        okText: _this.state.dict['mob.confirm'],
        cancelText: _this.state.dict['mob.cancel'],
        onOk() {
          window.close()
        },
@@ -73,50 +83,86 @@
    }
  }
  triggerSave = () => {
    const { config, openEdition, parentId } = this.state
  submitConfig = () => {
    const { config, openEdition } = this.state
    this.setState({
      saveIng: true
    if (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return
    }
    if (config.enabled && this.verifyConfig()) {
      config.enabled = false
    }
    let _config = fromJS(config).toJS()
    delete _config.fstMenuList
    delete _config.permFuncField
    delete _config.sysRoles
    delete _config.tableFields
    let funcs = []
    _config.components.forEach(component => {
      if (component.setting && component.setting.innerFunc) {
        funcs.push(`select '${_config.uuid}' as MenuID,'${component.setting.innerFunc}' as ProcName,'${component.setting.name}' as MenuName`)
      }
      if (component.action) {
        component.action.forEach(item => {
          if (!item.innerFunc) return
          funcs.push(`select '${_config.uuid}' as MenuID,'${item.innerFunc}' as ProcName,'${item.label}' as MenuName`)
        })
      }
    })
    let param = {
      func: 'sPC_TrdMenu_AddUpt',
      ParentID: parentId,
      MenuID: config.uuid,
      MenuNo: config.MenuNo,
      EasyCode: '',
      Template: '',
      MenuName: '',
      PageParam: '',
      LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(config))),
      // LText: _vals.func.map(item => `select '${menu.MenuID}' as MenuID,'${item.func}' as ProcName,'${item.label}' as MenuName`),
      // LTexttb: _tables.map(item => `select '${menu.MenuID}' as MenuID,'${item}' as tbName`),
      TypeCharOne: 'mob'
      FstID: _config.fstMenuId,
      SndID: _config.parentId,
      ParentID: _config.parentId,
      MenuID: _config.uuid,
      MenuNo: _config.MenuNo,
      EasyCode: _config.easyCode,
      Template: 'CustomPage',
      MenuName: _config.MenuName,
      PageParam: JSON.stringify({Template: 'CustomPage', OpenType: 'newtab'}),
      LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(_config))),
      LText: funcs.join(' union all '),
      LTexttb: '', // 表名
    }
    let _LText = ''
    // _LText = _LText.join(' union all ')
    let _LTexttb = ''
    // _LTexttb = _LTexttb.join(' union all ')
    param.LText = Utils.formatOptions(_LText)
    param.LTexttb = Utils.formatOptions(_LTexttb)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.LText = Utils.formatOptions(param.LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    if (openEdition) { // 版本管理
      param.open_edition = openEdition
    }
    this.setState({
      menuloading: true
    })
    Api.getSystemConfig(param).then(response => {
      if (response.status) {
        this.setState({
          oriConfig: fromJS(config).toJS(),
          openEdition: response.open_edition || '',
          saveIng: false
          menuloading: false
        })
        notification.success({
          top: 92,
          message: '保存成功',
          duration: 2
        })
      } else {
        this.setState({
          openEdition: response.open_edition || '',
          menuloading: false
        })
        notification.warning({
          top: 92,
          message: response.message,
@@ -124,77 +170,6 @@
        })
      }
    })
  }
  testFunc = () => {
    let datas = [{
      name: 'a',
      arr_field: 'MapCode,Country',
      par_tablename: '',
      type: '',
      primaryKey: 'MapCode',
      foreign_key: '',
      sql: `select MapCode,Country from @tc1`,
      script: `declare @tc1 table (MapCode nvarchar(50),Country nvarchar(50)) insert into @tc1 (MapCode,Country) select MapCode,Country from sMap where Province=''`
    }, {
      name: 'b',
      arr_field: 'MapCode,Province,ParMapCode',
      par_tablename: 'a',
      type: 'array',
      primaryKey: 'MapCode',
      foreign_key: 'ParMapCode',
      sql: `select MapCode,Province,ParMapCode from @tc2`,
      script: `declare @tc2 table (MapCode nvarchar(50),Province nvarchar(50),ParMapCode nvarchar(50)) insert into @tc2 (MapCode,Province,ParMapCode) select MapCode,Province,ParMapCode from sMap where Province!='' and City=''`
    }, {
      name: 'c',
      arr_field: 'MapCode,City,ParMapCode',
      par_tablename: 'b',
      type: 'array',
      primaryKey: 'MapCode',
      foreign_key: 'ParMapCode',
      sql: `select MapCode,City,ParMapCode from @tc3`,
      script: `declare @tc3 table (MapCode nvarchar(50),City nvarchar(50),ParMapCode nvarchar(50)) insert into @tc3 (MapCode,City,ParMapCode) select MapCode,City,ParMapCode from sMap where City!='' and Area=''`
    }, {
      name: 'd',
      arr_field: 'MapCode,Area,ParMapCode',
      par_tablename: 'c',
      type: 'array',
      primaryKey: 'MapCode',
      foreign_key: 'ParMapCode',
      sql: `select MapCode,Area,ParMapCode from sMap where Area!=''`,
      script: ``
    }]
    let LText = datas.map((item, index) => {
      // item.par_tablename = ''
      // item.foreign_key = ''
      let _orderBy = 'MapCode desc'
      let _search = ''
      let _sql = `select top 1000 ${item.arr_field} from (select ${item.arr_field} ,ROW_NUMBER() over(order by ${_orderBy}) as rows from (${item.sql}) tb ${_search}) tmptable order by tmptable.rows `
      return `Select '${item.name}' as tablename,'${window.btoa(window.encodeURIComponent(_sql))}' as LText,'${window.btoa(window.encodeURIComponent(item.script))}' as Lcustomize,'${item.type}' as table_type,'${item.primaryKey}' as primary_key,'${item.par_tablename}' as par_tablename,'${item.foreign_key}' as foreign_key,'${index}' as Sort`
    })
    let LText_field = []
    datas.forEach(item => {
      item.arr_field.split(',').forEach(cell => {
        LText_field.push(`Select '${item.name}' as tablename,'${cell}' as fieldname,'nvarchar(50)' as field_type`)
      })
    })
    let param = {
      func: 'sPC_Get_structured_data',
      LText: LText.join(' union all '),
      LText_field: LText_field.join(' union all ')
    }
    param.LText = Utils.formatOptions(param.LText)
    param.LText_field = Utils.formatOptions(param.LText_field)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    Api.getLocalConfig(param)
  }
  getMenuParam = () => {
@@ -218,6 +193,8 @@
          config = {
            version: 1.0,
            uuid: this.props.match.params.MenuId,
            MenuID: this.props.match.params.MenuId,
            parentId: this.props.match.params.ParentId,
            Template: 'CustomPage',
            easyCode: '',
            enabled: false,
@@ -226,12 +203,18 @@
            tables: [],
            components: []
          }
        } else {
          config.uuid = this.props.match.params.MenuId
          config.MenuID = this.props.match.params.MenuId
        }
        this.setState({
          oriConfig: config,
          config: fromJS(config).toJS(),
          openEdition: result.open_edition || '',
        })
        this.getRoleFields()
      } else {
        notification.warning({
          top: 92,
@@ -242,6 +225,44 @@
    })
  }
  getRoleFields = () => {
    Api.getSystemConfig({func: 'sPC_Get_Roles_sModular'}).then(res => {
      if (res.status) {
        let _permFuncField = []
        let _sysRoles = []
        if (res.Roles && res.Roles.length > 0) {
          _sysRoles = res.Roles.map(role => {
            return {
              uuid: Utils.getuuid(),
              value: role.RoleID,
              text: role.RoleName
            }
          })
        }
        if (res.sModular && res.sModular.length > 0) {
          res.sModular.forEach(field => {
            if (field.ModularNo) {
              _permFuncField.push(field.ModularNo)
            }
          })
          _permFuncField = _permFuncField.sort()
        }
        this.setState({
          config: {...this.state.config, sysRoles: _sysRoles, permFuncField: _permFuncField}
        })
      }
    })
  }
  initMenuList = (msg) => {
    this.setState({
      config: {...this.state.config, ...msg}
    })
  }
  deleteCard = (id) => {
    let _this = this
    let config = fromJS(this.state.config).toJS()
@@ -249,8 +270,6 @@
    confirm({
      title: '确定删除元素吗?',
      content: '',
      okText: this.state.dict['mob.confirm'],
      cancelText: this.state.dict['mob.cancel'],
      onOk() {
        config.components = config.components.filter(item => item.uuid !== id)
@@ -268,117 +287,133 @@
    })
  }
  updateStyle = (proper) => {
  onEnabledChange = () => {
    const { config } = this.state
    config.components = config.components.map(component => {
      if (component.uuid === proper.componentId) {
        Object.keys(component).forEach(key => {
          let _uuid = component[key].uuid
          if (_uuid && (_uuid === proper.uuid || _uuid === proper.classId)) {
            if (component[key].substyle) {
    if (!config.enabled && this.verifyConfig(true)) {
      return
    }
            } else {
              component[key].style = {...component[key].style, ...proper.style}
              // eslint-disable-next-line
              for (let index in component[key].style) {
                if (component[key].style[index] === '') {
                  delete component[key].style[index]
                }
              }
            }
          }
        })
      }
      return component
    this.setState({
      config: {...config, enabled: !config.enabled}
    })
    this.setState({config})
  }
  verifyConfig = (show) => {
    const { config } = this.state
    let error = ''
    if (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return 'false'
    }
    config.components.forEach(item => {
      if (!error && item.setting) {
        if (item.setting.interType === 'system' && item.setting.execute !== 'false' && !item.setting.dataresource) {
          error = `组件《${item.setting.name}》未设置数据源`
        } else if (item.setting.interType === 'system' && item.setting.execute === 'false' && item.scripts.length === 0) {
          error = `组件《${item.setting.name}》未设置数据源`
        } else if (item.setting.interType && !item.setting.primaryKey) {
          error = `组件《${item.setting.name}》未设置主键`
        }
      }
    })
    if (show && error) {
      notification.warning({
        top: 92,
        message: error,
        duration: 5
      })
    }
    return error
  }
  // 更新配置信息
  updateConfig = (config) => {
    this.setState({
      config: config
    })
  }
  updatetable = (config) => {
    // this.setState({
    //   config: config
    // })
  }
  save = () => {
    html2canvas(document.getElementById('view')).then(canvas => {
      let imgUri = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'); // 获取生成的图片的url
      window.location.href = imgUri; // 下载图片
  /**
   * @description 更新常用表信息,快捷添加后更新配置信息
   */
  updatetable = (config, fields) => {
    const { tableFields } = this.state
    config.tableFields = fields ? fields : tableFields
    this.setState({
      config: config,
      tableFields: fields ? fields : tableFields
    })
  }
  render () {
    const { activeKey, saveIng, dict, MenuId, config } = this.state
    const { activeKey, dict, MenuId, config } = this.state
    return (
      <div className="pc-menu-view" id="view">
        <Header view="design" closeView={this.closeView} triggerSave={this.triggerSave} saveIng={saveIng} />
        <DndProvider backend={HTML5Backend}>
          <div className="menu-body">
            <div className="menu-setting">
              <Collapse accordion activeKey={activeKey} bordered={false} onChange={(key) => this.setState({activeKey: key})}>
                {/* 基本信息 */}
                <Panel header={dict['mob.basemsg']} key="basedata">
                  {/* 菜单信息 */}
                  <MenuForm
                    dict={dict}
                    config={config}
                    MenuId={MenuId}
                    parentId={this.props.match.params.ParentId}
                    MenuName={this.props.match.params.MenuName}
                    MenuNo={this.props.match.params.MenuNo}
                    updateConfig={this.updateConfig}
                  />
                  {/* 表名添加 */}
                  {config ? <TableComponent
                    config={config}
                    // containerId="main-basedata"
                    updatetable={this.updatetable}
                  /> : null}
                </Panel>
                {/* 搜索条件添加 */}
                {/* <Panel header={dict['mob.component']} key="component">
                  <div className="search-element">
                    {Source.searchItems.map((item, index) => (<SourceElement key={index} content={item}/>))}
                  </div>
                  <FieldsComponent
                    config={config}
                    type="search"
                    tableFields={this.state.tableFields}
                    updatefield={this.updateconfig}
                  />
                </Panel> */}
              </Collapse>
              {/* <Tabs defaultActiveKey="1" animated={false} size="small">
                <TabPane tab="配置" key="1">
                  <Controller editElem={editElem} updateStyle={this.updateStyle} />
                </TabPane>
                <TabPane tab="数据源" key="2">
                  <DataSource config={config} updateConfig={this.updateConfig} />
                </TabPane>
              </Tabs> */}
            </div>
            <div className="menu-tool">
              <div className="menu-tool-content">
                <div className="plus-content">
                  <Icon type="plus-circle" />添 加 组 件
                </div>
                <div className="useable-component">
                  <SourceWrap appType="Menu" />
                </div>
      <ConfigProvider locale={_locale}>
        <div className="pc-menu-view" id="view">
          <Header view="design" closeView={this.closeView} />
          <DndProvider backend={HTML5Backend}>
            <div className="menu-body">
              <div className="menu-setting">
                <Collapse accordion activeKey={activeKey} bordered={false} onChange={(key) => this.setState({activeKey: key})}>
                  {/* 基本信息 */}
                  <Panel header={dict['mob.basemsg']} key="basedata">
                    {/* 菜单信息 */}
                    <MenuForm
                      dict={dict}
                      config={config}
                      MenuId={MenuId}
                      parentId={this.props.match.params.ParentId}
                      MenuName={this.props.match.params.MenuName}
                      MenuNo={this.props.match.params.MenuNo}
                      initMenuList={this.initMenuList}
                      updateConfig={this.updateConfig}
                    />
                    {/* 表名添加 */}
                    {config ? <TableComponent config={config} updatetable={this.updatetable}/> : null}
                  </Panel>
                  {/* 组件添加 */}
                  <Panel header={dict['mob.component']} key="component">
                    <SourceWrap />
                  </Panel>
                  {/* <Panel header={dict['mob.style']} key="style">
                    <Controller />
                  </Panel> */}
                </Collapse>
              </div>
              <div className="menu-tool-other"></div>
              <div className="menu-view">
                <Card title={
                  <div>
                    {config && config.MenuName}
                    <Icon type="redo" style={{marginLeft: '10px'}} title="刷新标签列表" onClick={() => this.reloadTab()} />
                  </div>
                } bordered={false} extra={
                  <div>
                    {config ? <Switch className="big" checkedChildren={dict['mob.enable']} unCheckedChildren={dict['mob.disable']} checked={config.enabled} onChange={this.onEnabledChange} /> : null}
                    <Button type="primary" onClick={this.submitConfig} loading={this.state.menuloading}>{dict['mob.save']}</Button>
                  </div>
                } style={{ width: '100%' }}>
                  {/* {config && config.components ? <MenuShell menu={config} handleList={this.updateConfig} deleteCard={this.deleteCard} /> : null} */}
                  {config && config.components ? <MenuShell name="Glass" menu={config} handleList={this.updateConfig} deleteCard={this.deleteCard} /> : null}
                </Card>
              </div>
            </div>
          </div>
        </DndProvider>
      </div>
          </DndProvider>
        </div>
      </ConfigProvider>
    )
  }
}
@@ -391,4 +426,4 @@
  return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Mobile)
export default connect(mapStateToProps, mapDispatchToProps)(MenuDesign)