king
2024-05-21 a4466960bfd628036aa2b6f9aa706f75215482bc
src/views/menudesign/index.jsx
@@ -4,20 +4,16 @@
import { is, fromJS } from 'immutable'
import moment from 'moment'
import HTML5Backend from 'react-dnd-html5-backend'
import { ConfigProvider, notification, Modal, Collapse, Card, Switch, Button, Typography } from 'antd'
import { ConfigProvider, notification, Modal, Collapse, Card, Switch, Button, Typography, Spin } from 'antd'
import { DoubleLeftOutlined, DoubleRightOutlined, EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons'
import html2canvas from 'html2canvas'
import md5 from 'md5'
import Api from '@/api'
import options from '@/store/options.js'
import Utils, { setGLOBFuncs } 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 MKEmitter from '@/utils/events.js'
import MenuUtils from '@/utils/utils-custom.js'
import { getTables, getFuncsAndInters } from '@/utils/utils-custom.js'
import asyncComponent from '@/utils/asyncComponent'
import '@/assets/css/design.scss'
@@ -30,6 +26,7 @@
const MenuForm = asyncComponent(() => import('./menuform'))
const HomeForm = asyncComponent(() => import('./homeform'))
const PopView = asyncComponent(() => import('./popview'))
const Header = asyncComponent(() => import('@/menu/header'))
const MenuShell = asyncComponent(() => import('@/menu/menushell'))
const PrintMenuForm = asyncComponent(() => import('./printmenuform'))
@@ -39,6 +36,8 @@
const PasteController = asyncComponent(() => import('@/menu/pastecontroller'))
const StyleController = asyncComponent(() => import('@/menu/stylecontroller'))
const ReplaceField = asyncComponent(() => import('@/menu/replaceField'))
const Debug = asyncComponent(() => import('@/menu/debug'))
const NormalCss = asyncComponent(() => import('@/menu/normalCss'))
const Versions = asyncComponent(() => import('@/menu/versions'))
const TableNodes = asyncComponent(() => import('@/menu/tablenodes'))
const SysInterface = asyncComponent(() => import('@/menu/sysinterface'))
@@ -49,45 +48,59 @@
const StyleCombControlButton = asyncComponent(() => import('@/menu/stylecombcontrolbutton'))
const TableComponent = asyncComponent(() => import('@/templates/sharecomponent/tablecomponent'))
sessionStorage.setItem('isEditState', 'true')
sessionStorage.setItem('appType', '')          // 应用类型
document.body.className = ''
class MenuDesign extends Component {
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    MenuType: '',
    MenuId: '',
    ParentId: '',
    MenuName: '',
    MenuNo: '',
    delButtons: [],
    copyButtons: [],
    activeKey: 'basedata',
    menuloading: false,
    oriConfig: null,
    config: null,
    customComponents: [],
    comloading: false,
    settingshow: true,
    settingshow: sessionStorage.getItem('settingshow') !== 'false',
    eyeopen: false,
    modalStatus: false       // 弹窗是否开启,判断ctrl+s是否可用
    view: '',
    popConfig: null,
    needUpdate: false
  }
  UNSAFE_componentWillMount() {
    if (sessionStorage.getItem('devError') === 'true') {
      sessionStorage.clear()
      window.history.replaceState(null, null, window.location.href.split('#')[0] + '#/login')
      window.location.reload()
      return
    }
    if (!sessionStorage.getItem('UserID')) {
      sessionStorage.removeItem('appType')
      this.props.history.replace('/login')
      return
    }
    sessionStorage.setItem('editMenuType', 'menu') // 编辑菜单类型
    window.GLOB.curDate = moment().format('YYYY-MM-DD')
    window.GLOB.UserComponentMap = new Map() // 缓存用户自定义组件
    window.GLOB.TabsMap = new Map()          // 缓存用户操作的标签页
    window.GLOB.urlFields = []               // url变量
    window.GLOB.customMenu = null            // 保存菜单信息
    window.GLOB.developing = true
    try {
      let param = JSON.parse(window.decodeURIComponent(window.atob(this.props.match.params.param)))
      sessionStorage.setItem('MenuType', param.MenuType || 'custom')
      this.setState({
        MenuType: param.MenuType,
        MenuId: param.MenuId,
        MenuId: param.MenuId || param.MenuID,
        ParentId: param.ParentId || '',
        MenuName: param.MenuName || '',
        MenuNo: param.MenuNo || '',
@@ -108,24 +121,12 @@
  }
  componentDidMount () {
    MKEmitter.addListener('delButtons', this.delButtons)
    MKEmitter.addListener('modalStatus', this.modalStatus)
    MKEmitter.addListener('copyButtons', this.copyButtons)
    if (!sessionStorage.getItem('UserID')) return
    MKEmitter.addListener('changePopview', this.initPopview)
    MKEmitter.addListener('triggerMenuSave', this.triggerMenuSave)
    MKEmitter.addListener('submitComponentStyle', this.updateComponentStyle)
    MKEmitter.addListener('updateCustomComponent', this.updateCustomComponent)
    MKEmitter.addListener('changeEditMenu', this.changeEditMenu)
    setTimeout(() => {
      if (sessionStorage.getItem('app_custom_components')) {
        let list = sessionStorage.getItem('app_custom_components')
        list = JSON.parse(list)
        this.setCustomComponent(list)
      } else {
        this.updateCustomComponent()
      }
      this.getAppPictures()
      this.getPrintTemp()
      this.getRoleFields()
      setGLOBFuncs()
    }, 1000)
@@ -149,16 +150,32 @@
      let _shortcut = `${preKey}+${keyCode}`
      if (_shortcut === 'ctrl+83') {
        if (this.state.modalStatus) {
        let modals = document.querySelectorAll('.mk-pop-modal')
        let msg = null
        for (let i = 0; i < modals.length; i++) {
          if (msg) {
            break
          }
          let node = modals[i].querySelector('.mk-com-name')
          if (node) {
            msg = node.innerText
          }
        }
        if (msg) {
          notification.warning({
            top: 92,
            message: '请保存' + this.state.modalStatus,
            message: '请保存' + msg,
            duration: 5
          })
          return false
        }
        let node = document.getElementById('save-modal-config')
        if (!node) {
          node = document.getElementById('save-pop-config')
        }
        if (!node) {
          node = document.getElementById('save-config')
        }
@@ -178,201 +195,119 @@
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('delButtons', this.delButtons)
    MKEmitter.removeListener('modalStatus', this.modalStatus)
    MKEmitter.removeListener('copyButtons', this.copyButtons)
    MKEmitter.removeListener('changePopview', this.initPopview)
    MKEmitter.removeListener('triggerMenuSave', this.triggerMenuSave)
    MKEmitter.removeListener('submitComponentStyle', this.updateComponentStyle)
    MKEmitter.removeListener('updateCustomComponent', this.updateCustomComponent)
    MKEmitter.removeListener('changeEditMenu', this.changeEditMenu)
  }
  modalStatus = (val) => {
    this.setState({modalStatus: val})
  }
  triggerMenuSave = () => {
    this.submitConfig()
  }
  getPrintTemp = () => {
    if (!sessionStorage.getItem('printTemps')) {
      let _sql = `select ID,Images,PrintTempNO+PrintTempName as PN from sPrintTemplate
      where appkey= @appkey@ and Deleted=0 and typechartwo='web_print'
      union select ID,Images,a.PrintTempNO+PrintTempName as PN
      from (select * from sPrintTemplate where appkey= '' and Deleted=0 and typechartwo='web_print') a
      left join (select PrintTempNO from sPrintTemplate where appkey= @appkey@ and Deleted=0 ) b
      on a.PrintTempNO=b.PrintTempNO
      left join (select Srcid from sPrintTemplate_Log where appkey='' and apicode= @appkey@ and Deleted=0 ) c
      on a.ID=c.Srcid where b.PrintTempNO is null and c.Srcid is null`
  changeEditMenu = (menu) => {
    if (menu.MenuID && menu.MenuID.length === 3 && menu.MenuNo && !this.menuLoading) {
      this.menuLoading = true
      let param = {
        func: 'sPC_Get_SelectedList',
        LText: Utils.formatOptions(_sql),
        obj_name: 'data',
        arr_field: 'PN,ID,Images'
        func: 'sPC_Get_LongParam',
        MenuID: menu.MenuID[2]
      }
  
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      Api.getCloudConfig(param).then(result => {
        this.menuLoading = false
        if (result.status) {
          let config = null
  
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp) // 云端数据验证
      Api.getSystemConfig(param).then(res => {
        if (res.status) {
          let temps = res.data.map(temp => {
            return {
              value: temp.ID,
              text: temp.PN
          try {
            config = result.LongParam ? JSON.parse(window.decodeURIComponent(window.atob(result.LongParam))) : null
          } catch (e) {
            console.warn('Parse Failure')
            config = null
          }
          if (config) {
            let _param = {
              MenuId: menu.MenuID[2],
              MenuID: menu.MenuID[2],
              ParentId: menu.MenuID[1],
              MenuName: menu.MenuName,
              MenuNo: menu.MenuNo
            }
          })
          sessionStorage.setItem('printTemps', JSON.stringify(temps))
        } else {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
            if (config.Template === 'BaseTable') {
              _param = window.btoa(window.encodeURIComponent(JSON.stringify(_param)))
              window.open(`#/tabledesign/${_param}`)
            } else if (config.Template === 'CustomPage') {
              _param.MenuType = 'custom'
              _param = window.btoa(window.encodeURIComponent(JSON.stringify(_param)))
              window.open(`#/menudesign/${_param}`)
            }
          }
        }
      })
    }
  }
  getAppPictures = () => {
    if (sessionStorage.getItem('app_videos') || sessionStorage.getItem('app_pictures')) return
    Api.getSystemConfig({
      func: 's_url_db_adduptdel',
      PageIndex: 0,  // 0 代表全部
      PageSize: 0,   // 0 代表全部
      typecharone: 'image',
      type: 'search'
    }).then(res => {
      if (res.status) {
        sessionStorage.setItem('app_pictures', JSON.stringify(res.data || []))
      }
  triggerMenuSave = () => {
    if (this.state.view === 'popview') return
      Api.getSystemConfig({
        func: 's_url_db_adduptdel',
        PageIndex: 0,  // 0 代表全部
        PageSize: 0,   // 0 代表全部
        typecharone: 'video',
        type: 'search'
      }).then(res => {
        if (res.status) {
          sessionStorage.setItem('app_videos', JSON.stringify(res.data || []))
        }
      })
      Api.getSystemConfig({
        func: 's_url_db_adduptdel',
        PageIndex: 0,  // 0 代表全部
        PageSize: 0,   // 0 代表全部
        typecharone: 'color',
        type: 'search'
      }).then(res => {
        if (res.status) {
          sessionStorage.setItem('app_colors', JSON.stringify(res.data || []))
        }
      })
    this.submitConfig()
  }
  submitPopConfig = (btnconfig) => {
    let parents = {[btnconfig.ParentId]: true}
    let popbtns = {[btnconfig.uuid]: fromJS(btnconfig).toJS()}
    let config = fromJS(this.state.config).toJS()
    config.components = this.setPopView(config.components, parents, popbtns)
    this.setState({ config }, () => {
      this.submitConfig()
    })
  }
  updateCustomComponent = () => {
    Api.getSystemConfig({
      func: 's_get_custom_components',
      typename: '',
      typecharone: ''
    }).then(res => {
      if (!res.status) {
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      } else if (res.cus_list) {
        sessionStorage.setItem('app_custom_components', JSON.stringify(res.cus_list))
        this.setCustomComponent(res.cus_list)
      }
    })
  }
  closePop = () => {
    const {config} = this.state
  setCustomComponent = (cus_list) => {
    let coms = []
    sessionStorage.setItem('editMenuType', 'menu')
    cus_list.forEach(item => {
      let config = ''
    window.GLOB.urlFields = config.urlFields || []
    window.GLOB.customMenu = config
      try {
        config = JSON.parse(window.decodeURIComponent(window.atob(item.long_param)))
      } catch (e) {
        console.warn('Parse Failure')
        config = ''
      }
      if (!config || !item.c_name) return
      window.GLOB.UserComponentMap.set(item.c_id, item.c_name)
      coms.push({
        uuid: item.c_id,
        type: 'menu',
        title: item.c_name,
        url: item.images,
        component: config.type,
        subtype: config.subtype,
        config
      })
    })
    this.setState({customComponents: coms})
  }
  updateComponentStyle = (parentId, keys, style) => {
    const { config } = this.state
    if (config.uuid !== parentId) return
    let components = config.components.map(item => {
      if (keys.includes(item.uuid)) {
        item.style = {...item.style, ...style}
      }
      return item
    })
    this.setState({
      config: {...config, components},
      comloading: true
    }, () => {
      this.setState({
        comloading: false
      })
    })
  }
  delButtons = (items) => {
    this.setState({ delButtons: [...this.state.delButtons, ...items] })
  }
  copyButtons = (items) => {
    this.setState({copyButtons: [...this.state.copyButtons, ...items]})
    this.setState({view: '', popConfig: null})
  }
  initPopview = (card, btn) => {
    const { oriConfig, config } = this.state
    const { config } = this.state
    if (!is(fromJS(oriConfig), fromJS(config))) {
    if (!this.checkBase()) {
      notification.warning({
        top: 92,
        message: '配置已修改,请保存!',
        message: '请完善基本信息!',
        duration: 5
      })
      return
    }
    let _btn = fromJS(btn).toJS()
    _btn.MenuName = config.MenuName + '-' + card.name + '-' + btn.label
    _btn.ParentMenuID = config.uuid
    this.props.history.push('/popdesign/' + window.btoa(window.encodeURIComponent((JSON.stringify(_btn)))))
    if (_btn.config) {
      _btn.config.uuid = _btn.uuid
      _btn.config.MenuID = _btn.uuid
      _btn.config.ParentId = card.uuid
      _btn.config.MenuName = _btn.label
      _btn.config.components = this.updateComponents(_btn.config.components || [])
    } else {
      _btn.config = {
        uuid: _btn.uuid,
        MenuID: _btn.uuid,
        ParentId: card.uuid,
        enabled: false,
        MenuName: _btn.label,
        tables: config.tables || [],
        Template: 'CustomPage',
        components: [],
        viewType: 'popview',
        style: { backgroundColor: '#ffffff', backgroundImage: '', paddingTop: '16px', paddingBottom: '40px', paddingLeft: '16px', paddingRight: '16px' }
      }
    }
    this.setState({view: 'popview', popConfig: _btn})
  }
  closeView = () => {
@@ -405,7 +340,7 @@
      MenuID: MenuId
    }
    Api.getSystemConfig(param).then(result => {
    Api.getCloudConfig(param).then(result => {
      if (result.status) {
        let config = null
@@ -418,7 +353,7 @@
        if (!config) {
          config = {
            version: 1.0,
            version: 2.0,
            uuid: MenuId,
            MenuID: MenuId,
            parentId: ParentId,
@@ -464,11 +399,21 @@
        config.open_edition = result.open_edition || ''
        window.GLOB.urlFields = config.urlFields || []
        this.setState({
          oriConfig: config,
          config: fromJS(config).toJS()
        })
        window.GLOB.customMenu = config
        if (config.version !== 2.0) {
          this.setState({
            oriConfig: fromJS(config).toJS(),
            comloading: true,
            needUpdate: true
          })
          this.updatePage(config)
        } else {
          config.components = this.updateComponents(config.components)
          this.setState({
            oriConfig: fromJS(config).toJS(),
            config: config
          })
          window.GLOB.customMenu = config
        }
      } else {
        notification.warning({
          top: 92,
@@ -479,8 +424,221 @@
    })
  }
  getMenuMessage = (delButtons, tbs) => {
    const { config } = this.state
  updateComponents = (components) => { // 兼容性升级 table
    return components.map(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          tab.components = this.updateComponents(tab.components)
        })
      } else if (item.type === 'group') {
        item.components = this.updateComponents(item.components)
      } else if (item.type === 'table') {
        item.cols = item.cols.map(col => {
          if (col.type === 'action') {
            col.type = 'custom'
          }
          return col
        })
      }
      return item
    })
  }
  collectTB = (components, popBtns) => {
    return components.map(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          delete tab.floor
          delete tab.hasSearch
          delete tab.parentId
          tab.components = this.collectTB(tab.components, popBtns)
        })
      } else if (item.type === 'group') {
        item.components = this.collectTB(item.components, popBtns)
      } else {
        item.$tables = getTables(item, popBtns)
      }
      if (item.subtype === 'tablecard') { // 兼容
        item.type = 'card'
      } else if (item.type === 'table') {
        item.cols = item.cols.map(col => {
          if (col.type === 'action') {
            col.type = 'custom'
          }
          return col
        })
      }
      delete item.tabId
      delete item.parentId
      delete item.btnlog
      delete item.floor
      delete item.dataName
      return item
    })
  }
  setPopView = (components, parents, popbtns) => {
    return components.map(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          tab.components = this.setPopView(tab.components, parents, popbtns)
        })
      } else if (item.type === 'group') {
        item.components = this.setPopView(item.components, parents, popbtns)
      } else if (parents[item.uuid]) {
        this.setpopConfig(item, popbtns)
      }
      return item
    })
  }
  setpopConfig = (config, popbtns) => {
    config.subcards && config.subcards.forEach(item => {
      item.elements.forEach(cell => {
        if (cell.eleType !== 'button') return
        if (cell.OpenType === 'popview' && popbtns[cell.uuid]) {
          cell.config = popbtns[cell.uuid]
        }
      })
    })
    if (config.cols) {
      let loopCol = (cols) => {
        cols.forEach(col => {
          if (col.type === 'colspan') {
            loopCol(col.subcols)
          } else if (col.type === 'custom') {
            col.elements.forEach(cell => {
              if (cell.eleType !== 'button') return
              if (cell.OpenType === 'popview' && popbtns[cell.uuid]) {
                cell.config = popbtns[cell.uuid]
              }
            })
          }
        })
      }
      loopCol(config.cols)
    }
    config.elements && config.elements.forEach(cell => {
      if (cell.eleType !== 'button') return
      if (cell.OpenType === 'popview' && popbtns[cell.uuid]) {
        cell.config = popbtns[cell.uuid]
      }
    })
    config.action && config.action.forEach(cell => {
      if (cell.OpenType === 'popview' && popbtns[cell.uuid]) {
        cell.config = popbtns[cell.uuid]
      }
    })
    config.$tables = getTables(config)
  }
  updatePage = (config) => {
    let popBtns = []
    config.components = this.collectTB(config.components, popBtns)
    config.version = 2.0
    if (popBtns.length === 0) {
      this.setState({
        config: config,
        comloading: false,
        needUpdate: true
      })
      window.GLOB.customMenu = config
      return
    }
    Promise.all(popBtns.map((pop, i) => {
      return new Promise(resolve => {
        let param = {
          func: 'sPC_Get_LongParam',
          MenuID: pop.uuid
        }
        setTimeout(() => {
          Api.getCloudConfig(param).then(res => {
            let _config = null
            try {
              _config = res.LongParam ? JSON.parse(window.decodeURIComponent(window.atob(res.LongParam))) : null
            } catch (e) {
              console.warn('Parse Failure')
              _config = null
            }
            if (_config && _config.Template !== 'CustomPage') {
              _config = null
            }
            if (_config) {
              _config.uuid = pop.uuid
              _config.MenuID = pop.uuid
              _config.ParentId = pop.parentId
              _config.MenuName = pop.label
              delete _config.MenuNo
              delete _config.open_edition
              delete _config.version
              _config.components = this.collectTB(_config.components)
            } else {
              _config = {
                uuid: pop.uuid,
                MenuID: pop.uuid,
                ParentId: pop.parentId,
                enabled: false,
                MenuName: pop.label,
                tables: config.tables || [],
                Template: 'CustomPage',
                components: [],
                viewType: 'popview',
                style: { backgroundColor: '#ffffff', backgroundImage: '', paddingTop: '16px', paddingBottom: '40px', paddingLeft: '16px', paddingRight: '16px' }
              }
            }
            resolve(_config)
          })
        }, i * 40)
      })
    })).then(results => {
      let bts = []
      results = results.map(res => {
        let tbs = []
        bts.push(...this.getMenuMessage(res, tbs))
        res.$tables = Array.from(new Set(tbs))
        return res
      })
      bts = bts.map(bt => bt.replace(/select\s'/, '').replace(/'\sas.*/, ''))
      bts.push(...popBtns.map(pop => pop.uuid))
      let parents = {}
      let popbtns = {}
      results.forEach(item => {
        parents[item.ParentId] = true
        popbtns[item.uuid] = item
      })
      config.components = this.setPopView(config.components, parents, popbtns)
      this.setState({ delButtons: bts, config, comloading: false })
      window.GLOB.customMenu = config
    })
  }
  getMenuMessage = (config, tbs) => {
    let buttons = []
    let _sort = 1
@@ -489,123 +647,128 @@
        if (item.$tables) {
          tbs.push(...item.$tables)
        }
        if (item.wrap && item.wrap.permission === 'false') {
          return
        }
        if (item.action && item.action.length > 0) {
          item.action.forEach(btn => {
            if (btn.hidden === 'true' || btn.permission === 'false') return
            buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
            _sort++
          })
        }
        if (item.type === 'tabs') {
          item.subtabs.forEach(tab => {
            traversal(tab.components)
          })
        } else if (item.type === 'group') {
          traversal(item.components)
        } else if (item.type === 'card' || (item.type === 'table' && item.subtype === 'tablecard')) {
          item.action && item.action.forEach(btn => {
            if (btn.hidden === 'true') {
              delButtons.push(btn.uuid)
              return
            }
            buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort`)
            _sort++
          })
        } else if (item.type === 'card' || item.type === 'carousel' || item.type === 'timeline') {
          item.subcards.forEach(card => {
            card.elements && card.elements.forEach(cell => {
              if (cell.eleType !== 'button') return
              if (cell.hidden === 'true') {
                delButtons.push(cell.uuid)
                return
              }
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
              if (cell.hidden === 'true' || cell.permission === 'false') return
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
              _sort++
            })
            card.backElements && card.backElements.forEach(cell => {
              if (cell.eleType !== 'button') return
              if (cell.hidden === 'true') {
                delButtons.push(cell.uuid)
                return
              }
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
              _sort++
            })
          })
        } else if (item.type === 'carousel' || item.type === 'timeline') {
          item.subcards.forEach(card => {
            card.elements && card.elements.forEach(cell => {
              if (cell.eleType !== 'button') return
              if (cell.hidden === 'true') {
                delButtons.push(cell.uuid)
                return
              }
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
              if (cell.hidden === 'true' || cell.permission === 'false') return
              buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
              _sort++
            })
          })
        } else if (item.type === 'balcony') {
          item.elements && item.elements.forEach(cell => {
            if (cell.eleType !== 'button') return
            if (cell.hidden === 'true') {
              delButtons.push(cell.uuid)
              return
            }
            buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort`)
            if (cell.hidden === 'true' || cell.permission === 'false') return
            buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
            _sort++
          })
        } else if (item.type === 'line' || item.type === 'bar' || item.type === 'chart') {
          item.action && item.action.forEach(btn => {
            if (btn.hidden === 'true') {
              delButtons.push(btn.uuid)
              return
            }
            buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort`)
            _sort++
          })
        } else if (item.type === 'table' && (item.subtype === 'normaltable' || item.subtype === 'editable')) {
          item.action && item.action.forEach(btn => {
            if (btn.hidden === 'true') {
              delButtons.push(btn.uuid)
              return
            }
            buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort`)
            _sort++
          })
          item.cols && item.cols.forEach(col => {
            if (col.type !== 'action') return
            col.elements.forEach(btn => {
              if (btn.hidden === 'true') {
                delButtons.push(btn.uuid)
                return
        } else if (item.type === 'table') {
          let loopCol = (cols) => {
            cols.forEach(col => {
              if (col.type === 'colspan') {
                loopCol(col.subcols)
              } else if (col.type === 'custom') {
                col.elements.forEach(cell => {
                  if (cell.eleType !== 'button' || cell.hidden === 'true' || cell.permission === 'false') return
                  buttons.push(`select '${cell.uuid}' as menuid, '${item.name + '-' + cell.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
                  _sort++
                })
              }
              buttons.push(`select '${btn.uuid}' as menuid, '${item.name + '-' + btn.label}' as menuname, '${_sort * 10}' as Sort`)
              _sort++
            })
          })
          }
          loopCol(item.cols)
        }
      })
    }
    traversal(config.components)
    if (config.interfaces) {
      config.interfaces.forEach(item => {
        if (item.$tables) {
          tbs.push(...item.$tables)
        }
      })
    }
    return buttons
  }
  checkBase = () => {
    const { MenuType, config } = this.state
    if (MenuType === 'billPrint' && ((config.printPage === 'page' && !config.everyPCount) || (config.callback === 'true' && !config.callNo))) {
      return false
    } else if (MenuType === 'home' && (config.cacheUseful === 'true' && !config.cacheTime)) {
      return false
    } else if (MenuType === 'custom' && (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId || (config.cacheUseful === 'true' && !config.cacheTime))) {
      return false
    }
    return true
  }
  resetSyncQuery = (components) => {
    return components.map(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          tab.components = this.resetSyncQuery(tab.components)
        })
      } else if (item.type === 'group') {
        item.components = this.resetSyncQuery(item.components)
      } else if (item.setting && item.setting.interType === 'system' && item.setting.sync === 'true') {
        let sql = ''
        if (item.setting.execute !== 'false' && item.setting.dataresource) {
          sql = item.setting.dataresource
        }
        item.scripts && item.scripts.forEach(script => {
          if (script.status === 'false') return
          sql += script.sql
        })
        if (sql.length > 8000) {
          item.setting.sync = 'false'
        }
      }
      return item
    })
  }
  submitConfig = () => {
    const { MenuType, copyButtons } = this.state
    const { MenuType } = this.state
    let config = fromJS(this.state.config).toJS()
    if (MenuType === 'billPrint' && config.printPage === 'page' && !config.everyPCount) {
    if (!this.checkBase()) {
      notification.warning({
        top: 92,
        message: '请完善基本信息!',
        duration: 5
      })
      return
    } else if (MenuType === 'home' && (config.cacheUseful === 'true' && !config.cacheTime)) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return
    } else if (MenuType === 'custom' && (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId || (config.cacheUseful === 'true' && !config.cacheTime))) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return
@@ -616,13 +779,31 @@
    })
    setTimeout(() => {
      if (config.enabled && this.verifyConfig()) {
      let _pass = this.verifyConfig(config)
      if (config.enabled && !_pass) {
        config.enabled = false
        config.force = true
      } else if (!config.enabled && config.force && _pass) {
        config.enabled = true
        delete config.force
      }
      if (config.cacheUseful !== 'true') {
        config.components = this.resetSyncQuery(config.components)
      }
      if (config.MenuID === 'home_page_id') {
        config.permission = 'false'
      }
      let tbs = []
      let delButtons = fromJS(this.state.delButtons).toJS()
      let btns = this.getMenuMessage(delButtons, tbs)
      let btns = this.getMenuMessage(config, tbs)
      if (config.permission === 'false') {
        btns = []
      }
      let arr = []
      tbs = tbs.filter(tb => {
        let _tb = tb.toLowerCase()
@@ -639,7 +820,7 @@
      }
      tbs = tbs.map(tb => `'${tb}'`).join(';')
      let key = md5(config.uuid + window.GLOB.appkey + tbs.toLowerCase())
      let key = md5(config.uuid + tbs.toLowerCase())
      let url = ''
      if (config.tbkey === key) {
@@ -651,6 +832,9 @@
        config.tbkey = key
      }
      let interfaces = getFuncsAndInters(config)
      let urlFields = config.urlFields ? config.urlFields.join(',') : ''
      let param = {
        func: 'sPC_TrdMenu_AddUpt',
        FstID: config.fstMenuId || '',
@@ -661,7 +845,7 @@
        EasyCode: config.easyCode || '',
        Template: 'CustomPage',
        MenuName: config.MenuName || '',
        PageParam: JSON.stringify({Template: 'CustomPage', OpenType: config.OpenType || 'newtab', hidden: config.hidden || 'false'}),
        PageParam: JSON.stringify({Template: 'CustomPage', OpenType: config.OpenType || 'newtab', hidden: config.hidden || 'false', menuColor: config.menuColor || '', interfaces, urlFields}),
        open_edition: config.open_edition,
        LText: '',
        LTexttb: '',
@@ -671,9 +855,8 @@
        LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(config)))
      }
      param.LText = Utils.formatOptions(param.LText)
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      param.secretkey = Utils.encrypt('', param.timestamp)
      let btnParam = {             // 添加菜单按钮
        func: 'sPC_Button_AddUpt',
@@ -681,24 +864,14 @@
        ParentID: config.uuid,
        MenuNo: config.MenuNo,
        Template: 'CustomPage',
        PageParam: '',
        LongParam: '',
        LText: []
        button_proc_edition: 'Y',
        exec_type: 'x'
      }
      let btnIds = '' // 用于复制按钮的过滤
      if (MenuType !== 'billPrint') {
        btnParam.LText = btns
        btnParam.LText = btnParam.LText.join(' union all ')
        btnIds = btnParam.LText
        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 = ''
      }
      btnParam.LText = btns.join(' union all ')
      btnParam.LText = Utils.formatOptions(btnParam.LText, 'x')
      btnParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      btnParam.secretkey = Utils.encrypt('', btnParam.timestamp)
      new Promise(resolve => {
        if (MenuType === 'billPrint') { // 打印生成页面效果图
@@ -707,222 +880,128 @@
              Base64Img: canvas.toDataURL('image/png') // 获取生成的图片
            }
  
            if (options.cloudServiceApi) {
              param.rduri = options.cloudServiceApi
            if (window.GLOB.cloudServiceApi) {
              param.rduri = window.GLOB.cloudServiceApi
              param.userid = sessionStorage.getItem('CloudUserID') || ''
              param.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
            }
  
            Api.fileuploadbase64(param).then(result => {
              if (result.status) {
                Api.getSystemConfig({
                let url = result.Images
                let baseurl = ''
                if (window.GLOB.cloudServiceApi) {
                  baseurl = window.GLOB.cloudServiceApi.replace(/webapi(.*)$/, '')
                } else {
                  baseurl = window.GLOB.baseurl
                }
                url = url.match(/^http/) || url.match(/^\/\//) ? url : baseurl + url
                Api.getCloudConfig({
                  func: 's_PrintTemplateMSub',
                  ID: config.uuid,
                  Images: Utils.getcloudurl(result.Images),
                  Images: url,
                  Remark: '',
                  temp_type: 'billprint',
                }).then(response => {
                  if (response.status) {
                    resolve(true)
                  } else {
                    notification.warning({
                      top: 92,
                      message: response.message,
                      duration: 5
                    })
                    resolve(false)
                  }
                  resolve(response)
                })
              } else {
                notification.warning({
                  top: 92,
                  message: result.ErrMesg,
                  duration: 5
                })
                resolve(false)
                resolve(result)
              }
            })
            }, this.netError)
          })
        } else {
          resolve(true)
          resolve({status: true})
        }
      }).then(res => { // 按钮删除
        if (!res) return
      }).then(res => { // 页面保存
        if (!res || !res.status) return res
        if (delButtons.length === 0) {
        return Api.getCloudConfig(param)
      }).then(res => { // 按钮删除
        if (!res || !res.status) return res
        if (MenuType !== 'billPrint') { // 基本信息改变时,通知菜单列表更新
          localStorage.setItem('menuUpdate', new Date().getTime() + ',' + config.uuid)
        }
        config.open_edition = res.open_edition || ''
        this.setState({
          config,
          oriConfig: fromJS(config).toJS(),
          needUpdate: false
        })
        if (this.state.delButtons.length === 0) {
          return {
            status: true
          }
        } else {
          let _param = {
            func: 'sPC_MainMenu_Del',
            MenuID: delButtons.join(',')
            MenuID: this.state.delButtons.join(',')
          }
          return Api.getSystemConfig(_param)
          return Api.getCloudConfig(_param)
        }
      }).then(res => { // 页面保存
        if (!res) return
      }, this.netError).then(res => { // 页面按钮关系保存
        if (!res || !res.status) return res
        if (res.status) {
          return Api.getSystemConfig(param)
        this.setState({
          delButtons: []
        })
        if (MenuType !== 'billPrint') {
          return Api.getCloudConfig(btnParam)
        } else {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
          return false
        }
      }).then(res => { // 页面按钮关系保存
        if (!res) return
        if (res.status) {
          if (MenuType !== 'billPrint') { // 基本信息改变时,通知菜单列表更新
            let ori = this.state.oriConfig
            if (config.MenuName !== ori.MenuName || config.MenuNo !== ori.MenuNo || config.parentId !== ori.parentId) {
              localStorage.setItem('menuUpdate', new Date().getTime())
            }
          }
          config.open_edition = res.open_edition || ''
          this.setState({
            config,
            oriConfig: fromJS(config).toJS(),
          })
          if (btnParam.LText) {
            return Api.getSystemConfig(btnParam)
          } else {
            return {
              status: true
            }
          }
        } else {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
          return false
        }
      }).then(res => { // 按钮复制
        if (!res) return
        if (!res.status) {
          notification.warning({
            top: 92,
            message: res.message,
            duration: 5
          })
          return false
        }
        if (copyButtons.length === 0) {
          return {
            status: true
          }
        } else {
          return new Promise(resolve => {
            let deffers = copyButtons.map(item => {
              return new Promise(resolve => {
                if (btnIds.indexOf(item.uuid) === -1) { // 复制的按钮已删除
                  resolve({
                    status: true
                  })
                  return
                }
                Api.getSystemConfig({
                  func: 'sPC_Get_LongParam',
                  MenuID: item.$originUuid
                }).then(result => {
                  if (result.status) {
                    let _conf = ''
                    try {
                      _conf = result.LongParam ? JSON.parse(window.decodeURIComponent(window.atob(result.LongParam))) : ''
                    } catch (e) {
                      console.warn('Parse Failure')
                      _conf = ''
                    }
                    if (_conf) {
                      _conf.components = MenuUtils.resetConfig(_conf.components)
                      _conf.uuid = item.uuid
                      _conf.MenuID = item.uuid
                      _conf.Template = 'CustomPage'
                      _conf.enabled = false
                    } else {
                      resolve({
                        status: true
                      })
                      return
                    }
                    let _param = {
                      func: 'sPC_ButtonParam_AddUpt',
                      ParentID: config.uuid,
                      MenuID: item.uuid,
                      MenuNo: '',
                      Template: 'CustomPage',
                      MenuName: item.label,
                      PageParam: JSON.stringify({Template: 'CustomPage'}),
                      LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(_conf)))
                    }
                    Api.getSystemConfig(_param).then(response => {
                      resolve(response)
                    })
                  }
                })
              })
            })
            Promise.all(deffers).then(result => {
              let error = null
              result.forEach(response => {
                if (!response.status) {
                  error = response
                }
              })
              if (error) {
                notification.warning({
                  top: 92,
                  message: error.message,
                  duration: 5
                })
                resolve(false)
              } else {
                resolve({
                  status: true
                })
              }
            })
          })
        }
      }).then(res => {
        if (res && res.status) {
          this.setState({
            delButtons: [],
            copyButtons: [],
            menuloading: false
          })
      }, this.netError).then(res => {
        this.setState({
          menuloading: false
        })
        if (!res) return
        if (res.status) {
          notification.success({
            top: 92,
            message: '保存成功',
            duration: 2
          })
        } else {
          this.setState({
            menuloading: false
          Modal.warning({
            width: 400,
            title: res.message,
            okText: '知道了'
          })
        }
        MKEmitter.emit('completeSave')
      })
      }, this.netError)
    }, 300 + (+sessionStorage.getItem('mkDelay')))
  }
  netError = (error) => {
    this.setState({
      menuloading: false
    })
    if (!error) {
      notification.warning({
        top: 92,
        message: '保存失败,请检查网络是否正常。',
        duration: 5
      })
    }
    MKEmitter.emit('completeSave')
  }
  getRoleFields = () => {
    if (sessionStorage.getItem('sysRoles') || sessionStorage.getItem('permFuncField')) return
    Api.getSystemConfig({func: 'sPC_Get_Roles_sModular'}).then(res => {
    if (sessionStorage.getItem('sysRoles')) return
    Api.getCloudConfig({func: 'sPC_Get_Roles_sModular'}).then(res => {
      if (res.status) {
        let _permFuncField = []
        let _sysRoles = []
@@ -955,17 +1034,23 @@
  onEnabledChange = () => {
    const { config } = this.state
    if (!config || (!config.enabled && this.verifyConfig(true))) {
      return
    }
    let _config = {...config, enabled: !config.enabled}
    this.setState({
      config: {...config, enabled: !config.enabled}
    })
    delete _config.force
    if (!_config.enabled) {
      this.setState({
        config: _config
      })
    } else if (this.verifyConfig(_config)) {
      this.setState({
        config: _config
      })
    }
  }
  verifyConfig = (show) => {
    const { config, MenuType } = this.state
  verifyConfig = (config) => {
    const { MenuType } = this.state
    let error = ''
    let check = (components) => {
@@ -993,7 +1078,7 @@
    check(config.components)
    if (show && error) {
    if (config.enabled && error) {
      notification.warning({
        top: 92,
        message: error,
@@ -1009,12 +1094,14 @@
        carousel: '轮播',
        tree: '树形列表',
        chart: '自定义图表',
        editor: '富文本',
        group: '分组'
        // editor: '富文本',
        group: '分组',
        iframe: 'iframe'
      }
      let subforbid = {
        editable: '可编辑表格',
        voucher: '凭证'
        voucher: '凭证',
        account: '账套'
      }
      config.components.forEach(item => {
@@ -1025,7 +1112,7 @@
        }
      })
      if (show && error) {
      if (config.enabled && error) {
        notification.warning({
          top: 92,
          message: error,
@@ -1034,7 +1121,7 @@
      }
    }
    return error
    return error === ''
  }
  // 更新配置信息
@@ -1064,65 +1151,81 @@
    this.setState({config})
    window.GLOB.customMenu = config
    notification.success({
      top: 92,
      message: '粘贴成功!',
      duration: 2
    })
  }
  changeSetting = () => {
    this.setState({settingshow: !this.state.settingshow})
    sessionStorage.setItem('settingshow', '' + !this.state.settingshow)
    setTimeout(() => {
      MKEmitter.emit('tabsChange', 'all')
    }, 400)
  }
  checklog = () => {
    const { oriConfig, config } = this.state
    return is(fromJS(oriConfig), fromJS(config))
  }
  updateLogConfig = (config) => {
    config.fstMenuId = this.state.config.fstMenuId || config.fstMenuId || ''
    config.parentId = this.state.config.parentId || config.parentId || ''
    config.open_edition = this.state.config.open_edition || ''
    this.setState({
      config: null
    }, () => {
      this.setState({
        config: config
      })
    })
    window.GLOB.customMenu = config
  }
  render () {
    const { activeKey, comloading, MenuType, dict, MenuId, config, settingshow, ParentId, menuloading, customComponents, eyeopen } = this.state
    const { view, comloading, MenuType, MenuId, config, settingshow, ParentId, menuloading, eyeopen, needUpdate } = this.state
    return (
      <ConfigProvider locale={_locale}>
        <div className={'pc-menu-view ' + (MenuType || '')}>
          <Header />
          <DndProvider backend={HTML5Backend}>
        <Header menuName={config ? config.MenuName : ''}/>
        <DndProvider backend={HTML5Backend}>
          {view !== 'popview' ? <div className={'pc-menu-view ' + (MenuType || '')}>
            <div className="menu-body">
              <div className={'menu-setting ' + (!settingshow ? 'hidden' : '')}>
                <div className="draw">
                  {settingshow ? <DoubleLeftOutlined onClick={this.changeSetting}/> : <DoubleRightOutlined onClick={this.changeSetting}/>}
                </div>
                <Collapse accordion activeKey={activeKey} bordered={false} onChange={(key) => this.setState({activeKey: key})}>
                <Collapse accordion defaultActiveKey="basedata" bordered={false}>
                  {/* 基本信息 */}
                  <Panel header="基本信息" key="basedata">
                    {/* 菜单信息 */}
                    {config && MenuType === 'custom' ? <MenuForm
                      dict={dict}
                      config={config}
                      MenuId={MenuId}
                      parentId={ParentId}
                      MenuName={config.MenuName}
                      MenuNo={config.MenuNo}
                      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 ? <UrlFieldComponent
                      config={config}
                      updateConfig={this.updateConfig}
                    /> : null}
                    {/* 表名添加 */}
                    {config ? <TableComponent config={config} updatetable={this.updateConfig}/> : null}
                    {config ? <Paragraph style={{padding: '15px 0px 0px 18px'}} copyable={{ text: MenuId }}>菜单ID</Paragraph> : null}
                    {config ? <>
                      {MenuType === 'custom' ? <MenuForm
                        config={config}
                        MenuId={MenuId}
                        parentId={ParentId}
                        MenuName={config.MenuName}
                        MenuNo={config.MenuNo}
                        updateConfig={this.updateConfig}
                      /> : null}
                      {MenuType === 'home' ? <HomeForm
                        config={config}
                        updateConfig={this.updateConfig}
                      /> : null}
                      {MenuType === 'billPrint' ? <PrintMenuForm
                        config={config}
                        updateConfig={this.updateConfig}
                      /> : null}
                      <UrlFieldComponent
                        config={config}
                        updateConfig={this.updateConfig}
                      />
                      {/* 表名添加 */}
                      <TableComponent config={config} updatetable={this.updateConfig}/>
                      <Paragraph style={{padding: '15px 0px 0px 18px'}} copyable={{ text: MenuId }}>菜单ID</Paragraph>
                      <NormalCss config={config} updateConfig={this.updateConfig}/>
                    </> : null}
                  </Panel>
                  {/* 组件添加 */}
                  <Panel header="组件" key="component">
@@ -1131,39 +1234,37 @@
                  <Panel header="元素" key="element">
                    <Modulecell />
                  </Panel>
                  {customComponents && customComponents.length ? <Panel header="自定义组件" key="cuscomponent">
                    <SourceWrap components={customComponents} MenuType={MenuType} />
                  </Panel> : null}
                  <Panel header="页面样式" key="background">
                    {config ? <BgController config={config} updateConfig={this.updateConfig} /> : null}
                  </Panel>
                </Collapse>
              </div>
              <div className={'menu-view' + (menuloading ? ' saving' : '') + (eyeopen ? ' eye-open' : '')}>
                <Card title={config ? config.MenuName : ''} bordered={false} extra={
                <Card bordered={false} extra={
                  <div className="mk-opeartion-list">
                    {config ? <Debug config={config}/> : null}
                    <Button className="mk-border-purple" onClick={() => this.setState({eyeopen: !eyeopen})}>{!eyeopen ? <EyeOutlined /> : <EyeInvisibleOutlined />} 组件名</Button>
                    <Versions MenuId={MenuId} open_edition={config ? config.open_edition : ''}/>
                    {config ? <Versions MenuId={MenuId} Template="CustomPage" checklog={this.checklog} updateConfig={this.updateLogConfig}/> : null}
                    <TableNodes config={config} />
                    <ReplaceField type="custom" config={config} updateConfig={this.resetConfig}/>
                    <SysInterface config={config} updateConfig={this.updateConfig}/>
                    <PictureController/>
                    <StyleCombControlButton menu={config} />
                    <PasteController insert={this.insert} />
                    <Switch className="big" checkedChildren={dict['mob.enable']} unCheckedChildren={dict['mob.disable']} checked={config && config.enabled} onChange={this.onEnabledChange} />
                    <Button type="primary" id="save-config" onClick={this.submitConfig} loading={menuloading}>{dict['mob.save']}</Button>
                    {config ? <Switch className="big" checkedChildren="启" unCheckedChildren="停" checked={config.enabled} onChange={this.onEnabledChange} /> : null}
                    <Button type="primary" id="save-config" className={needUpdate ? 'update-tip' : ''} onClick={this.submitConfig} loading={menuloading}>保存</Button>
                    <Button type="default" onClick={this.closeView}>关闭</Button>
                  </div>
                } style={{ width: '100%' }}>
                  {config && !comloading ? <MenuShell menu={config} handleList={this.updateConfig} /> : null}
                  {config && !comloading ? <MenuShell menu={config} handleList={this.updateConfig} /> : <Spin className="loading-config" size="large" />}
                </Card>
              </div>
            </div>
          </DndProvider>
          <StyleController />
          <StyleCombController />
          <ModalController />
        </div>
          </div> : <PopView btn={this.state.popConfig} save={this.submitPopConfig} cancel={this.closePop}/>}
        </DndProvider>
        <ModalController />
        <StyleController />
        <StyleCombController />
      </ConfigProvider>
    )
  }