king
2020-11-18 d3272e82652361e5e9bd045925222ef042b6731f
src/views/menudesign/index.jsx
@@ -4,7 +4,8 @@
import { is, fromJS } from 'immutable'
import moment from 'moment'
import HTML5Backend from 'react-dnd-html5-backend'
import { ConfigProvider, notification, Modal, Collapse, Card, Icon, Switch, Button } from 'antd'
import { ConfigProvider, notification, Modal, Collapse, Card, Switch, Button } from 'antd'
import html2canvas from 'html2canvas'
import Api from '@/api'
import Utils from '@/utils/utils.js'
@@ -13,40 +14,65 @@
import antdEnUS from 'antd/es/locale/en_US'
import antdZhCN from 'antd/es/locale/zh_CN'
import asyncComponent from '@/utils/asyncComponent'
import { modifyCustomMenu, initPermission } from '@/store/action'
import './index.scss'
// const { TabPane } = Tabs
const { Panel } = Collapse
const { confirm } = Modal
const _locale = localStorage.getItem('lang') !== 'en-US' ? antdZhCN : antdEnUS
const MenuForm = asyncComponent(() => import('./menuform'))
const HomeForm = asyncComponent(() => import('./homeform'))
const PrintMenuForm = asyncComponent(() => import('./printmenuform'))
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 DataSource = asyncComponent(() => import('@/mob/datasource'))
const BgController = asyncComponent(() => import('@/menu/bgcontroller'))
const PaddingController = asyncComponent(() => import('@/menu/padcontroller'))
const StyleController = asyncComponent(() => import('@/menu/stylecontroller'))
const ModalController = asyncComponent(() => import('@/menu/modalconfig/controller'))
const TableComponent = asyncComponent(() => import('@/templates/sharecomponent/tablecomponent'))
sessionStorage.setItem('isEditState', 'true')
sessionStorage.setItem('delButtons', JSON.stringify([]))
class MenuDesign extends Component {
  state = {
    dict: localStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    MenuId: this.props.match.params.MenuId,
    MenuType: '',
    MenuId: '',
    ParentId: '',
    MenuName: '',
    MenuNo: '',
    tableFields: [],
    activeKey: 'basedata',
    menuloading: false,
    oriConfig: null,
    openEdition: '',
    config: null,
    editElem: null
  }
  UNSAFE_componentWillMount() {
    this.getMenuParam()
    // this.testFunc()
    try {
      let param = JSON.parse(window.decodeURIComponent(window.atob(this.props.match.params.param)))
      this.setState({
        MenuType: param.MenuType,
        MenuId: param.MenuId,
        ParentId: param.ParentId || '',
        MenuName: param.MenuName || '',
        MenuNo: param.MenuNo || '',
      }, () => {
        this.getMenuParam()
      })
    } catch {
      notification.warning({
        top: 92,
        message: '菜单信息解析错误!',
        duration: 5
      })
    }
  }
  shouldComponentUpdate (nextProps, nextState) {
@@ -62,14 +88,16 @@
    }
  }
  reloadTab = () => {
  }
  closeView = () => {
    const { oriConfig, config } = this.state
    if (!is(fromJS(oriConfig), fromJS(config))) {
    let _config = fromJS(config).toJS()
    delete _config.fstMenuList
    delete _config.permFuncField
    delete _config.sysRoles
    delete _config.tableFields
    if (!is(fromJS(oriConfig), fromJS(_config))) {
      confirm({
        title: '配置已修改,放弃保存吗?',
        content: '',
@@ -83,10 +111,141 @@
    }
  }
  getMenuParam = () => {
    const { MenuId, ParentId, MenuName, MenuNo, MenuType } = this.state
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: MenuId
    }
    Api.getSystemConfig(param).then(result => {
      if (result.status) {
        let config = null
        try {
          config = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
        } catch (e) {
          console.warn('Parse Failure')
          config = null
        }
        if (!config) {
          config = {
            version: 1.0,
            uuid: MenuId,
            MenuID: MenuId,
            parentId: ParentId,
            Template: 'CustomPage',
            easyCode: '',
            enabled: false,
            MenuName: MenuName,
            MenuNo: MenuNo,
            tables: [],
            components: [],
            style: {
              backgroundColor: '#ffffff', backgroundImage: '',
              paddingTop: '16px', paddingBottom: '80px', paddingLeft: '16px', paddingRight: '16px'
            },
            MenuType: MenuType
          }
          if (MenuType === 'billPrint') {
            config.style.paddingTop = '50px'
            config.style.paddingBottom = '50px'
            config.style.paddingLeft = '30px'
            config.style.paddingRight = '30px'
          }
        } else {
          config.uuid = MenuId
          config.MenuID = MenuId
          config.MenuType = config.MenuType || MenuType
        }
        if (MenuType === 'billPrint') {
          config.fstMenuId = 'BillPrintTemp'
          config.parentId = 'BillPrintTemp'
          config.MenuName = MenuName
          config.MenuNo = MenuNo
          config.firstCount = config.firstCount || 5
          config.everyPCount = config.everyPCount || 5
          config.lastCount = config.lastCount || ''
        }
        this.setState({
          oriConfig: config,
          config: fromJS(config).toJS(),
          openEdition: result.open_edition || '',
        })
        this.getRoleFields()
      } else {
        notification.warning({
          top: 92,
          message: result.message,
          duration: 5
        })
      }
    })
  }
  getMenuMessage = () => {
    const { config } = this.state
    let buttons = []
    let _sort = 1
    let traversal = (components) => {
      components.forEach(item => {
        if (item.type === 'tabs') {
          item.subtabs.forEach(tab => {
            traversal(tab.components)
          })
        } else if (item.type === 'card' || (item.type === 'table' && item.subtype === 'tablecard')) {
          item.subcards.forEach(card => {
            card.elements && card.elements.forEach(cell => {
              if (cell.eleType !== 'button') return
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
              _sort++
            })
            card.backElements && card.backElements.forEach(cell => {
              if (cell.eleType !== 'button') return
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
              _sort++
            })
          })
        } else if (item.type === 'line' || item.type === 'bar') {
          item.action && item.action.forEach(btn => {
            buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort`)
            _sort++
          })
        }
      })
    }
    traversal(config.components)
    return buttons
  }
  submitConfig = () => {
    const { config, openEdition } = this.state
    if (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId) {
    if (config.MenuType === 'billPrint' && (!config.firstCount || !config.everyPCount)) {
      notification.warning({
        top: 92,
        message: '请完善基本信息!',
        duration: 5
      })
      return
    } else if (config.MenuType === 'home' && (config.cacheUseful === 'true' && !config.cacheTime)) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return
    } else if (config.MenuType === 'custom' && (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId || (config.cacheUseful === 'true' && !config.cacheTime))) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
@@ -105,33 +264,20 @@
    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',
      FstID: _config.fstMenuId,
      FstID: _config.fstMenuId || '',
      SndID: _config.parentId,
      ParentID: _config.parentId,
      MenuID: _config.uuid,
      MenuNo: _config.MenuNo,
      EasyCode: _config.easyCode,
      MenuNo: _config.MenuNo || '',
      EasyCode: _config.easyCode || '',
      Template: 'CustomPage',
      MenuName: _config.MenuName,
      MenuName: _config.MenuName || '',
      PageParam: JSON.stringify({Template: 'CustomPage', OpenType: 'newtab'}),
      LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(_config))),
      LText: funcs.join(' union all '),
      LTexttb: '', // 表名
      LText: '',
      LTexttb: ''
    }
    param.LText = Utils.formatOptions(param.LText)
@@ -142,86 +288,102 @@
      param.open_edition = openEdition
    }
    let btnParam = {             // 添加菜单按钮
      func: 'sPC_Button_AddUpt',
      Type: 40,                  // 添加菜单下的按钮type为40,按钮下的按钮type为60
      ParentID: _config.uuid,
      MenuNo: _config.MenuNo,
      Template: 'CustomPage',
      PageParam: '',
      LongParam: '',
      LText: []
    }
    if (config.MenuType !== 'billPrint') {
      btnParam.LText = this.getMenuMessage()
      btnParam.LText = btnParam.LText.join(' union all ')
      btnParam.LText = Utils.formatOptions(btnParam.LText)
      btnParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      btnParam.secretkey = Utils.encrypt(btnParam.LText, btnParam.timestamp)
    } else {
      btnParam.LText = ''
    }
    this.setState({
      menuloading: true
    })
    Api.getSystemConfig(param).then(response => {
      if (response.status) {
        this.setState({
          oriConfig: fromJS(config).toJS(),
          openEdition: response.open_edition || '',
          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,
          duration: 5
        })
      }
    })
  }
  getMenuParam = () => {
    Api.getSystemConfig({
      func: 'sPC_Get_LongParam',
      MenuID: this.props.match.params.MenuId
    }).then(result => {
      if (result.status) {
        let config = null
        if (result.LongParam) {
          try {
            config = JSON.parse(window.decodeURIComponent(window.atob(result.LongParam)))
          } catch (e) {
            console.warn('Parse Failure')
            config = null
          }
        }
        if (!config) {
          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,
            MenuName: this.props.match.params.MenuName,
            MenuNo: this.props.match.params.MenuNo,
            tables: [],
            components: []
          }
    }, () => {
      new Promise(resolve => {
        if (config.MenuType === 'billPrint') {
          html2canvas(document.getElementById('menu-shell-inner')).then(canvas => {
            let img = canvas.toDataURL('image/png') // 获取生成的图片
            Api.fileuploadbase64(img, 'cloud').then(result => {
              if (result.status) {
                Api.getSystemConfig({
                  func: 's_PrintTemplateMSub',
                  ID: _config.uuid,
                  Images: Utils.getcloudurl(result.Images),
                  Remark: '',
                  temp_type: 'billprint',
                }).then(response => {
                  if (response.status) {
                    resolve(true)
                  } else {
                    notification.warning({
                      top: 92,
                      message: response.message,
                      duration: 5
                    })
                    this.setState({
                      menuloading: false
                    })
                    resolve(false)
                  }
                })
              } else {
                notification.warning({
                  top: 92,
                  message: result.ErrMesg,
                  duration: 5
                })
                this.setState({
                  menuloading: false
                })
                resolve(false)
              }
            })
          })
        } else {
          config.uuid = this.props.match.params.MenuId
          config.MenuID = this.props.match.params.MenuId
          resolve(true)
        }
      }).then(res => {
        if (!res) return
        this.setState({
          oriConfig: config,
          config: fromJS(config).toJS(),
          openEdition: result.open_edition || '',
        Api.getSystemConfig(param).then(response => {
          if (response.status) {
            this.setState({
              oriConfig: fromJS(_config).toJS(),
              openEdition: response.open_edition || '',
              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,
              duration: 5
            })
          }
        })
        this.getRoleFields()
      } else {
        notification.warning({
          top: 92,
          message: result.message,
          duration: 5
        })
      }
      })
    })
  }
@@ -250,41 +412,19 @@
          _permFuncField = _permFuncField.sort()
        }
        this.setState({
          config: {...this.state.config, sysRoles: _sysRoles, permFuncField: _permFuncField}
        })
        let config = {...this.state.config, sysRoles: _sysRoles, permFuncField: _permFuncField}
        this.setState({config})
        this.props.modifyCustomMenu(config)
      }
    })
  }
  initMenuList = (msg) => {
    this.setState({
      config: {...this.state.config, ...msg}
    })
  }
    let config = {...this.state.config, ...msg}
  deleteCard = (id) => {
    let _this = this
    let config = fromJS(this.state.config).toJS()
    confirm({
      title: '确定删除元素吗?',
      content: '',
      onOk() {
        config.components = config.components.filter(item => item.uuid !== id)
        _this.setState({
          config: config
        })
      },
      onCancel() {}
    })
  }
  editCard = (element) => {
    this.setState({
      editElem: element
    })
    this.setState({config})
    this.props.modifyCustomMenu(config)
  }
  onEnabledChange = () => {
@@ -303,23 +443,22 @@
    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 (error) return
      if (item.subtype === 'propcard' && item.wrap.datatype === 'static') return
      if (item.setting) {
        if (item.setting.interType === 'system' && item.setting.execute !== 'false' && !item.setting.dataresource) {
          error = `组件《${item.setting.name}》未设置数据源`
          error = `组件《${item.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}》未设置主键`
          error = `组件《${item.name}》未设置数据源!`
        } else if (item.setting.interType && !item.setting.primaryKey && config.MenuType !== 'billPrint') {
          error = `组件《${item.name}》未设置主键!`
        }
      }
      if (item.type === 'bar' || item.type === 'line' || item.type === 'pie') {
        if (!item.plot.Xaxis) {
          error = `组件《${item.name}》图表字段尚未设置!`
        }
      }
    })
@@ -340,6 +479,8 @@
    this.setState({
      config: config
    })
    this.props.modifyCustomMenu(config)
  }
  /**
@@ -351,20 +492,20 @@
    config.tableFields = fields ? fields : tableFields
    this.setState({
      config: config,
      tableFields: fields ? fields : tableFields
      tableFields: fields ? fields : tableFields,
      config
    })
    this.props.modifyCustomMenu(config)
  }
  render () {
    const { activeKey, dict, MenuId, config } = this.state
    const { activeKey, MenuType, dict, MenuId, config, ParentId, MenuName, MenuNo, menuloading } = this.state
    return (
      <ConfigProvider locale={_locale}>
        <div className="pc-menu-view" id="view">
          <Header view="design" closeView={this.closeView} />
          <Header />
          <DndProvider backend={HTML5Backend}>
            <div className="menu-body">
              <div className="menu-setting">
@@ -372,46 +513,58 @@
                  {/* 基本信息 */}
                  <Panel header={dict['mob.basemsg']} key="basedata">
                    {/* 菜单信息 */}
                    <MenuForm
                    {config && MenuType === 'custom' ? <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}
                      parentId={ParentId}
                      MenuName={MenuName}
                      MenuNo={MenuNo}
                      initMenuList={this.initMenuList}
                      updateConfig={this.updateConfig}
                    />
                    /> : null}
                    {config && MenuType === 'home' ? <HomeForm
                      dict={dict}
                      config={config}
                      updateConfig={this.updateConfig}
                    /> : null}
                    {config && MenuType === 'billPrint' ? <PrintMenuForm
                      dict={dict}
                      config={config}
                      updateConfig={this.updateConfig}
                    /> : null}
                    {/* 表名添加 */}
                    {config ? <TableComponent config={config} updatetable={this.updatetable}/> : null}
                  </Panel>
                  {/* 组件添加 */}
                  <Panel header={dict['mob.component']} key="component">
                    <SourceWrap />
                    <SourceWrap MenuType={MenuType} />
                  </Panel>
                  {/* <Panel header={dict['mob.style']} key="style">
                    <Controller />
                  </Panel> */}
                  <Panel header={'背景'} key="background">
                    {config ? <BgController config={config} updateConfig={this.updateConfig} /> : null}
                  </Panel>
                  <Panel header={'内边距'} key="padding">
                    {config ? <PaddingController config={config} updateConfig={this.updateConfig} /> : null}
                  </Panel>
                </Collapse>
              </div>
              <div className="menu-view">
              <div className={'menu-view ' + (menuloading ? 'saving' : '')}>
                <Card title={
                  <div>
                    {config && config.MenuName}
                    <Icon type="redo" style={{marginLeft: '10px'}} title="刷新标签列表" onClick={() => this.reloadTab()} />
                  </div>
                  <div> {config && config.MenuName} </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>
                    <Button type="primary" onClick={this.submitConfig} loading={menuloading}>{dict['mob.save']}</Button>
                    <Button type="default" onClick={this.closeView}>{dict['mob.return']}</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}
                  {config && config.components ? <MenuShell menu={config} handleList={this.updateConfig} /> : null}
                </Card>
              </div>
            </div>
          </DndProvider>
          <StyleController />
          <ModalController />
        </div>
      </ConfigProvider>
    )
@@ -422,8 +575,11 @@
  return {}
}
const mapDispatchToProps = () => {
  return {}
const mapDispatchToProps = (dispatch) => {
  return {
    modifyCustomMenu: (customMenu) => dispatch(modifyCustomMenu(customMenu)),
    initPermission: (sysRoles, permFuncField) => dispatch(initPermission(sysRoles, permFuncField))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(MenuDesign)