king
2024-06-21 2bccb9ec7bdefe23292a22bc153463cfa1479a49
src/views/tabledesign/index.jsx
@@ -1,46 +1,102 @@
import React, {Component} from 'react'
import { notification, Spin, ConfigProvider } from 'antd'
import enUS from 'antd/es/locale/en_US'
import zhCN from 'antd/es/locale/zh_CN'
import React, { Component } from 'react'
import { DndProvider } from 'react-dnd'
import { withRouter } from 'react-router'
import { is, fromJS } from 'immutable'
import moment from 'moment'
import HTML5Backend from 'react-dnd-html5-backend'
import { notification, Modal, Collapse, Card, Switch, Button, Typography } from 'antd'
import { DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons'
import md5 from 'md5'
import Api from '@/api'
import Utils, { setGLOBFuncs } from '@/utils/utils.js'
import { langs } from '@/store/options'
import MKEmitter from '@/utils/events.js'
import { getTables, getFuncsAndInters, getLangTrans } from '@/utils/utils-custom.js'
import SourceElement from '@/templates/zshare/dragsource'
import asyncComponent from '@/utils/asyncComponent'
import asyncLoadComponent from '@/utils/asyncLoadComponent'
import Source from './source'
import '@/assets/css/design.scss'
import './index.scss'
const _locale = sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS
const Header = asyncComponent(() => import('@/menu/header'))
const ComTableConfig = asyncLoadComponent(() => import('@/templates/comtableconfig'))
const ModalConfig = asyncLoadComponent(() => import('@/templates/modalconfig'))
const { Panel } = Collapse
const { confirm } = Modal
const { Paragraph } = Typography
const MenuForm = asyncComponent(() => import('./menuform'))
const PopView = asyncComponent(() => import('./popview'))
const TableNodes = asyncComponent(() => import('@/menu/tablenodes'))
const TableSource = asyncComponent(() => import('./tablesource'))
const Header = asyncComponent(() => import('@/menu/header'))
const MenuShell = asyncComponent(() => import('@/menu/tableshell'))
const BgController = asyncComponent(() => import('@/pc/bgcontroller'))
const StyleController = asyncComponent(() => import('@/menu/stylecontroller'))
const ReplaceField = asyncComponent(() => import('@/menu/replaceField'))
const Debug = asyncComponent(() => import('@/menu/debug'))
const Versions = asyncComponent(() => import('@/menu/versions'))
const Transfer = asyncComponent(() => import('@/menu/transfer'))
const Unattended = asyncComponent(() => import('@/templates/zshare/unattended'))
const UrlFieldComponent = asyncComponent(() => import('@/menu/urlfieldcomponent'))
const ModalController = asyncComponent(() => import('@/menu/modalconfig/controller'))
const TableComponent = asyncComponent(() => import('@/templates/sharecomponent/tablecomponent'))
const PasteBaseTable = asyncComponent(() => import('@/menu/components/share/pastebasetable'))
sessionStorage.setItem('appType', '')          // 应用类型
document.body.className = ''
sessionStorage.setItem('isEditState', 'true')
class TableDesign extends Component {
  state = {
    loading: false,         // 编辑菜单或使用已使用模板时,获取配置信息
    btnParam: null,         // 编辑按钮的配置信息
    menulist: null,         // 编辑中的菜单
    tabview: '',            // 选择模板窗口(template)、基础表格配置(CommonTable)、表单(Modal)、子表(SubTable)
    editMenu: null,         // 编辑菜单
    editAction: null,       // 编辑按钮
    editTab: null,          // 编辑标签
    tabConfig: null,        // 标签配置信息
    editSubTab: null,       // 编辑子标签(标签中的标签)
    subTabConfig: null,     // 子标签配置信息
    subConfig: null,        // 子配置信息
    btnTab: null,           // 打开新标签或当前页面刷新的按钮
    btnTabConfig: null,     // 打开新标签按钮配置
    handleMVisible: false,  // 添加或修改菜单模态框(角色权限分配等)
    sysMenu: null,          // 添加或编辑菜单(角色权限分配等)
    change: false
    MenuId: '',
    ParentId: '',
    MenuName: '',
    MenuNo: '',
    activeKey: 'basedata',
    menuloading: false,
    oriConfig: null,
    config: null,
    comloading: false,
    settingshow: sessionStorage.getItem('settingshow') !== 'false',
    view: null,
    langName: '',
    popConfig: null
  }
  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)))
      this.getMenuParam(param)
      this.setState({
        MenuId: param.MenuID,
        ParentId: param.ParentId || '',
        MenuName: param.MenuName || '',
        MenuNo: param.MenuNo || '',
        langName: sessionStorage.getItem('lang') !== 'zh-CN' && langs[sessionStorage.getItem('lang')] ? `(${langs[sessionStorage.getItem('lang')]})` : ''
      }, () => {
        this.getMenuParam()
      })
    } catch (e) {
      notification.warning({
        top: 92,
@@ -50,101 +106,75 @@
    }
  }
  getMenuParam = (editMenu) => {
    editMenu.fstMenuId = editMenu.FstId
    editMenu.supMenuList = []
    editMenu.fstMenuList = []
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.state), fromJS(nextState))
  }
    let tree = sessionStorage.getItem('menuTree')
    if (tree) {
      tree = JSON.parse(tree)
      editMenu.fstMenuList = tree
  componentDidMount () {
    if (!sessionStorage.getItem('UserID')) return
    MKEmitter.addListener('changePopview', this.initPopview)
    MKEmitter.addListener('triggerMenuSave', this.triggerMenuSave)
    setTimeout(() => {
      this.getRoleFields()
      setGLOBFuncs()
    }, 1000)
      tree.forEach(item => {
        if (item.MenuID === editMenu.FstId) {
          editMenu.supMenuList = item.children
        }
      })
    }
    document.onkeydown = (event) => {
      let e = event || window.event
      let keyCode = e.keyCode || e.which || e.charCode
      let preKey = ''
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: editMenu.MenuID
    }
    this.setState({
      loading: true
    })
    Api.getSystemConfig(param).then(res => {
      if (res.status) {
        editMenu.open_edition = res.open_edition || ''
        editMenu.LongParam = ''
        if (res.LongParam) {
          let _LongParam = ''
          try {
            _LongParam = JSON.parse(window.decodeURIComponent(window.atob(res.LongParam)))
          } catch (e) {
            console.warn('Parse Failure')
            _LongParam = ''
          }
          editMenu.LongParam = _LongParam
        } else if (editMenu.PageParam.copyMenuId) {
          let _param = {
            func: 'sPC_Get_LongParam',
            MenuID: editMenu.PageParam.copyMenuId
          }
          Api.getSystemConfig(_param).then(res => {
            if (res.status) {
              if (res.LongParam) {
                let _LongParam = ''
                try {
                  _LongParam = JSON.parse(window.decodeURIComponent(window.atob(res.LongParam)))
                  _LongParam.type = 'user'
                } catch (e) {
                  console.warn('Parse Failure')
                  _LongParam = ''
                }
                editMenu.LongParam = _LongParam
              }
              this.setState({
                editMenu: editMenu,
                loading: false,
                tabview: editMenu.type
              })
            } else {
              this.setState({
                loading: false
              })
              notification.warning({
                top: 92,
                message: res.message,
                duration: 5
              })
            }
          })
          return
        }
        this.setState({
          editMenu: editMenu,
          loading: false,
          tabview: editMenu.type
        })
      } else {
        this.setState({
          loading: false
        })
        notification.warning({
          top: 92,
          message: res.message,
          duration: 5
        })
      if (e.ctrlKey) {
        preKey = 'ctrl'
      }
    })
      if (e.shiftKey) {
        preKey = 'shift'
      } else if (e.altKey) {
        preKey = 'alt'
      }
      if (!preKey || !keyCode) return
      let _shortcut = `${preKey}+${keyCode}`
      if (_shortcut === 'ctrl+83') {
        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: '请保存' + 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')
        }
        if (node) {
          node.click()
        }
        return false
      }
    }
  }
  /**
@@ -154,53 +184,764 @@
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('changePopview', this.initPopview)
    MKEmitter.removeListener('triggerMenuSave', this.triggerMenuSave)
  }
  handleView = (param) => {
    this.setState({
      tabview: ''
    }, () => {
      if (param) {
        this.setState(param)
  triggerMenuSave = () => {
    if (this.state.view === 'popview') return
    this.submitConfig()
  }
  initPopview = (card, btn) => {
    const { config } = this.state
    if (!this.checkBase()) {
      return
    }
    let _btn = fromJS(btn).toJS()
    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 = _btn.config.components || []
      _btn.config.components.forEach(item => {
        if (item.type === 'tabs') {
          item.subtabs.forEach(tab => {
            tab.components[0].cols = tab.components[0].cols.map(col => {
              if (col.type === 'action') {
                col.type = 'custom'
              }
              return col
            })
          })
        } else if (item.cols) {
          item.cols = item.cols.map(col => {
            if (col.type === 'action') {
              col.type = 'custom'
            }
            return col
          })
        }
      })
    } else {
      _btn.config = {
        uuid: _btn.uuid,
        MenuID: _btn.uuid,
        ParentId: card.uuid,
        enabled: false,
        MenuName: _btn.label,
        tables: config.tables || [],
        Template: 'BaseTable',
        components: [{
          uuid: Utils.getuuid(),
          type: 'table',
          width: 24,
          name: '主表',
          subtype: 'basetable',
          isNew: true
        }],
        viewType: 'popview',
        style: { backgroundColor: '#ffffff', backgroundImage: '', paddingTop: '16px', paddingBottom: '40px', paddingLeft: '16px', paddingRight: '16px' }
      }
    }
    this.setState({view: 'popview', popConfig: _btn})
  }
  submitPopConfig = (btnconfig) => {
    let config = fromJS(this.state.config).toJS()
    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' && cell.uuid === btnconfig.uuid) {
              cell.config = btnconfig
            }
          })
        }
      })
    }
    config.components.forEach(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          if (btnconfig.ParentId !== tab.components[0].uuid) return
          tab.components[0].action.forEach(btn => {
            if (btn.OpenType === 'popview' && btn.uuid === btnconfig.uuid) {
              btn.config = btnconfig
            }
          })
          loopCol(tab.components[0].cols)
          tab.components[0].$tables = getTables(tab.components[0])
        })
      } else if (item.uuid === btnconfig.ParentId) {
        item.action.forEach(btn => {
          if (btn.OpenType === 'popview' && btn.uuid === btnconfig.uuid) {
            btn.config = btnconfig
          }
        })
        loopCol(item.cols)
        item.$tables = getTables(item)
      }
    })
    this.setState({ config }, () => {
      this.submitConfig()
    })
  }
  closePop = () => {
    const { config } = this.state
    sessionStorage.setItem('editMenuType', 'menu')
    window.GLOB.urlFields = config.urlFields || []
    window.GLOB.customMenu = config
    this.setState({view: '', popConfig: null})
  }
  closeView = () => {
    const { oriConfig, config } = this.state
    if (!config) {
      window.close()
      return
    }
    if (!is(fromJS(oriConfig), fromJS(config))) {
      confirm({
        title: '配置已修改,放弃保存吗?',
        content: '',
        onOk() {
          window.close()
        },
        onCancel() {}
      })
    } else {
      window.close()
    }
  }
  getMenuParam = () => {
    const { MenuId, ParentId, MenuName, MenuNo } = this.state
    let param = {
      func: 'sPC_Get_LongParam',
      MenuID: MenuId
    }
    Api.getCloudConfig(param).then(result => {
      if (result.status) {
        let config = null
        try {
          config = result.LongParam ? JSON.parse(window.decodeURIComponent(window.atob(result.LongParam))) : null
        } catch (e) {
          console.warn('Parse Failure')
          config = null
        }
        if (!config) {
          config = {
            version: 1.0,
            uuid: MenuId,
            MenuID: MenuId,
            parentId: ParentId,
            Template: 'BaseTable',
            easyCode: '',
            enabled: false,
            MenuName: MenuName,
            MenuNo: MenuNo,
            tables: [],
            components: [
              {
                uuid: Utils.getuuid(),
                type: 'table',
                width: 24,
                name: '主表',
                subtype: 'basetable',
                isNew: true
              }
            ],
            viewType: 'menu',
            style: { backgroundColor: '#ffffff', paddingTop: '16px', paddingBottom: '80px', paddingLeft: '16px', paddingRight: '16px'},
          }
        } else {
          if (config.Template === 'CommonTable' && !config.components) {
            let urlparam = JSON.parse(window.decodeURIComponent(window.atob(this.props.match.params.param)))
            urlparam.type = 'CommonTable'
            if (urlparam.PageParam) {
              urlparam.PageParam.Template = 'CommonTable'
            }
            urlparam = window.btoa(window.encodeURIComponent(JSON.stringify(urlparam)))
            let url = `#/basedesign/${urlparam}`
            window.history.replaceState(null, null, window.location.href.split('#')[0] + url)
            window.location.reload()
            return
          }
          config.uuid = MenuId
          config.MenuID = MenuId
          config.Template = 'BaseTable'
          config.components.forEach(item => {
            if (item.type === 'tabs') {
              item.subtabs.forEach(tab => {
                tab.components[0].name = tab.label
                tab.components[0].cols = tab.components[0].cols.map(col => {
                  if (col.type === 'action') {
                    col.type = 'custom'
                  }
                  return col
                })
              })
            } else {
              item.cols = item.cols.map(col => {
                if (col.type === 'action') {
                  col.type = 'custom'
                }
                return col
              })
              item.name = '主表'
            }
          })
        }
        config.open_edition = result.open_edition || ''
        window.GLOB.urlFields = config.urlFields || []
        this.setState({
          oriConfig: config.components[0].isNew ? {} : fromJS(config).toJS(),
          config: config
        })
        window.GLOB.customMenu = config
      } else {
        window.close()
        notification.warning({
          top: 92,
          message: result.message,
          duration: 5
        })
      }
    })
  }
  getMenuMessage = (tbs) => {
    const { config } = this.state
    let buttons = []
    let _sort = 1
    config.components.forEach(item => {
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          if (tab.components[0].$tables) {
            tbs.push(...tab.components[0].$tables)
          }
          if (tab.permission !== 'true' || tab.hide === 'true') return
          buttons.push(`select '${tab.components[0].uuid}' as menuid, '${tab.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
          _sort++
          let _s = 1
          tab.components[0].action.forEach(btn => {
            if (btn.hidden === 'true' || btn.permission === 'false') return
            buttons.push(`select '${btn.uuid}' as menuid, '${btn.label}' as menuname, '${_s * 10}' as Sort, '${tab.components[0].uuid}' as parentid, 60 as Type`)
            _s++
          })
          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, '${cell.label}' as menuname, '${_s * 10}' as Sort, '${tab.components[0].uuid}' as parentid, 60 as Type`)
                  _s++
                })
              }
            })
          }
          loopCol(tab.components[0].cols)
        })
      } else {
        if (item.$tables) {
          tbs.push(...item.$tables)
        }
        item.action.forEach(btn => {
          if (btn.hidden === 'true' || btn.permission === 'false') return
          buttons.push(`select '${btn.uuid}' as menuid, '${btn.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
          _sort++
        })
        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,  '${cell.label}' as menuname, '${_sort * 10}' as Sort, '${config.uuid}' as parentid, 40 as Type`)
                _sort++
              })
            }
          })
        }
        loopCol(item.cols)
      }
    })
    return buttons
  }
  checkBase = () => {
    const { config } = this.state
    if (!config.MenuName || !config.MenuNo || !config.fstMenuId || !config.parentId) {
      notification.warning({
        top: 92,
        message: '请完善菜单基本信息!',
        duration: 5
      })
      return false
    }
    return true
  }
  submitConfig = () => {
    let config = fromJS(this.state.config).toJS()
    if (!this.checkBase()) {
      return
    } else if (this.checklog()) {
      if (sessionStorage.getItem('langList') && !config.trans) {
      } else {
        notification.success({
          top: 92,
          message: '当前配置未修改,无需保存。',
          duration: 5
        })
        MKEmitter.emit('completeSave')
        return
      }
    }
    this.setState({
      menuloading: true
    })
    setTimeout(() => {
      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
      }
      let tbs = []
      let btns = this.getMenuMessage(tbs)
      let arr = []
      tbs = tbs.filter(tb => {
        let _tb = tb.toLowerCase()
        if (arr.includes(_tb)) return false
        arr.push(_tb)
        return true
      })
      tbs.sort()
      if (tbs.length && sessionStorage.getItem('mk_tb_names')) {
        let names = sessionStorage.getItem('mk_tb_names')
        tbs = tbs.filter(tb => names.indexOf(',' + tb.toLowerCase() + ',') > -1)
      }
      tbs = tbs.map(tb => `'${tb}'`).join(';')
      let key = md5(config.uuid + tbs.toLowerCase())
      let url = ''
      if (config.tbkey === key) {
        key = ''
      } else {
        let urlparam = JSON.parse(window.decodeURIComponent(window.atob(this.props.match.params.param)))
        urlparam.type = 'admin'
        urlparam.MenuType = 'BaseTable'
        url = window.btoa(window.encodeURIComponent(JSON.stringify(urlparam)))
        config.tbkey = key
      }
      let interfaces = getFuncsAndInters(config)
      let urlFields = config.urlFields ? config.urlFields.join(',') : ''
      let langSql = getLangTrans(config)
      let param = {
        func: 'sPC_TrdMenu_AddUpt',
        FstID: config.fstMenuId || '',
        SndID: config.parentId,
        ParentID: config.parentId,
        MenuID: config.uuid,
        MenuNo: config.MenuNo || '',
        EasyCode: config.easyCode || '',
        Template: 'BaseTable',
        MenuName: config.MenuName || '',
        PageParam: JSON.stringify({Template: 'BaseTable', OpenType: config.OpenType || 'newtab', hidden: config.hidden || 'false', menuColor: config.menuColor || '', interfaces, urlFields}),
        open_edition: config.open_edition,
        // LText: '',
        // LTexttb: '',
        debug_md5: key,
        debug_url: url,
        debug_list: window.btoa(tbs),
        LongParam: window.btoa(window.encodeURIComponent(JSON.stringify(config)))
      }
      if (langSql) {
        param.lang_translation = window.btoa(window.encodeURIComponent(langSql))
      }
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.secretkey = Utils.encrypt('', param.timestamp)
      let btnParam = {             // 添加菜单按钮
        func: 'sPC_Button_AddUpt',
        Type: 40,                  // 添加菜单下的按钮type为40,按钮下的按钮type为60
        ParentID: config.uuid,
        MenuNo: config.MenuNo,
        Template: 'BaseTable',
        button_proc_edition: 'Y',
        exec_type: 'x'
      }
      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 => {
        Api.getCloudConfig(param).then(res => {
          resolve(res)
        }, this.netError)
      }).then(res => {
        if (!res || !res.status) return res
        localStorage.setItem('menuUpdate', new Date().getTime() + ',' + config.uuid)
        config.open_edition = res.open_edition || ''
        this.setState({
          config,
          oriConfig: fromJS(config).toJS(),
        })
        return Api.getCloudConfig(btnParam)
      }).then(res => {
        this.setState({
          menuloading: false
        })
        if (!res) return
        if (res.status) {
          notification.success({
            top: 92,
            message: '保存成功',
            duration: 2
          })
        } else {
          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')) return
    Api.getCloudConfig({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()
        }
        sessionStorage.setItem('sysRoles', JSON.stringify(_sysRoles))
        sessionStorage.setItem('permFuncField', JSON.stringify(_permFuncField))
      }
    })
  }
  onEnabledChange = () => {
    const { config } = this.state
    let _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 = (config) => {
    let error = ''
    config.components.forEach(item => {
      if (error) return
      if (item.type === 'tabs') {
        item.subtabs.forEach(tab => {
          if (!tab.components[0].errors || tab.components[0].errors.length === 0 || error) return
          tab.components[0].errors.forEach(err => {
            if (err.level !== 0 || error) return
            error = `子表《${tab.label}》${err.detail}`
          })
        })
      } else {
        item.errors.forEach(err => {
          if (err.level !== 0 || error) return
          error = `主表 ${err.detail}`
        })
      }
    })
    if (!error && config.autoMatic && config.autoMatic.enable === 'true') {
      let pass = false
      config.components[0].action.forEach(item => {
        if (item.uuid === config.autoMatic.action && (['pop', 'prompt', 'exec'].includes(item.OpenType) || (item.OpenType === 'funcbutton' && item.funcType === 'print'))) {
          pass = true
        }
      })
      if (!pass) {
        error = '无人值守设置无效!'
      }
    }
    if (config.enabled && error) {
      notification.warning({
        top: 92,
        message: error,
        duration: 5
      })
    }
    return error === ''
  }
  // 更新配置信息
  updateConfig = (config) => {
    this.setState({
      config: config
    })
    window.GLOB.customMenu = config
  }
  resetConfig = (config) => {
    this.setState({
      config,
      comloading: true
    }, () => {
      this.setState({
        comloading: false
      })
    })
    window.GLOB.customMenu = config
  }
  insert = (item) => {
    let config = fromJS(this.state.config).toJS()
    let tabs = {
      uuid: Utils.getuuid(),
      type: 'tabs',
      subtype: 'tabletabs',
      width: 24,
      setting: {},
      style: {},
      subtabs: [
        { uuid: Utils.getuuid(), label: item.name || '子表1', icon: '', components: [item] },
      ]
    }
    config.components.push(tabs)
    this.setState({config})
    window.GLOB.customMenu = config
  }
  changeSetting = () => {
    this.setState({settingshow: !this.state.settingshow})
    sessionStorage.setItem('settingshow', '' + !this.state.settingshow)
  }
  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 { loading } = this.state
    const { view, activeKey, comloading, MenuId, config, settingshow, ParentId, menuloading, langName } = this.state
    return (
      <div className="mk-base-design-wrap">
        <ConfigProvider locale={_locale}>
          <Header/>
          {this.state.tabview === 'CommonTable' ?
            <ComTableConfig
              menu={this.state.editMenu}
              reloadmenu={() => {localStorage.setItem('menuUpdate', new Date().getTime())}}
              handleView={this.handleView}
            /> : null
          }
          {this.state.tabview === 'Modal' ?
            <ModalConfig
              menu={this.state.editMenu}
              editTab={this.state.editTab}
              tabConfig={this.state.tabConfig}
              editSubTab={this.state.editSubTab}
              subTabConfig={this.state.subTabConfig}
              btnTab={this.state.btnTab}
              btnTabConfig={this.state.btnTabConfig}
              editAction={this.state.editAction}
              subConfig={this.state.subConfig}
              handleView={this.handleView}
            /> : null
          }
          {loading ? <Spin className="loading-view" size="large"/> : null}
        </ConfigProvider>
      </div>
      <>
        <Header menuName={config ? config.MenuName + langName : ''}/>
        <DndProvider backend={HTML5Backend}>
        {view !== 'popview' ? <div className="pc-table-view">
            <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})}>
                  {/* 基本信息 */}
                  <Panel header="基本信息" key="basedata">
                    {config ? <>
                      <MenuForm
                        config={config}
                        MenuId={MenuId}
                        parentId={ParentId}
                        MenuName={config.MenuName}
                        MenuNo={config.MenuNo}
                        updateConfig={this.updateConfig}
                      />
                      <UrlFieldComponent
                        config={config}
                        updateConfig={this.updateConfig}
                      />
                      {/* 表名添加 */}
                      <TableComponent config={config} updatetable={this.updateConfig}/>
                      <Paragraph style={{padding: '15px 0px 0px 18px'}} copyable={{ text: MenuId }}>菜单ID</Paragraph>
                    </> : null}
                  </Panel>
                  <Panel header="搜索" key="search">
                    {Source.searchItems.map((item, index) => (<SourceElement key={index} content={item}/>))}
                  </Panel>
                  <Panel header="按钮" key="action">
                    {Source.actionItems.map((item, index) => (<SourceElement key={index} content={item}/>))}
                  </Panel>
                  <Panel header="显示列" key="cols">
                    {Source.columnItems.map((item, index) => (<SourceElement key={index} content={item}/>))}
                  </Panel>
                  <Panel header="组件" key="component">
                    {Source.menuItems.map((item, index) => (<TableSource key={index} item={item}/>))}
                  </Panel>
                  <Panel header="页面样式" key="background">
                    {config ? <BgController config={config} updateConfig={this.updateConfig} /> : null}
                  </Panel>
                </Collapse>
              </div>
              <div className={'menu-view' + (menuloading ? ' saving' : '')}>
                <Card bordered={false} extra={
                  <div className="mk-opeartion-list">
                    {/* <Dropdown overlay={
                      <div className="mk-button-dropdown-wrap">
                        <ReplaceField type="custom" config={config} updateConfig={this.resetConfig}/>
                      </div>
                    } trigger={['click']} placement="bottomCenter">
                      <Button className="mk-button-more">更多<DownOutlined/></Button>
                    </Dropdown> */}
                    {config ? <Debug config={config}/> : null}
                    {config ? <Transfer config={config}/> : null}
                    {config ? <Unattended config={config} updateConfig={this.updateConfig}/> : null}
                    {config ? <Versions MenuId={MenuId} Template="BaseTable" checklog={this.checklog} updateConfig={this.updateLogConfig}/> : null}
                    <TableNodes config={config} />
                    <ReplaceField type="custom" config={config} updateConfig={this.resetConfig}/>
                    <PasteBaseTable type="page" insert={this.insert}/>
                    {config ? <Switch className="big" checkedChildren="启" unCheckedChildren="停" checked={config.enabled} onChange={this.onEnabledChange} /> : null}
                    <Button type="primary" id="save-config" 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}
                </Card>
              </div>
            </div>
          </div> : <PopView btn={this.state.popConfig} save={this.submitPopConfig} cancel={this.closePop}/>}
        </DndProvider>
        <StyleController />
        <ModalController />
      </>
    )
  }
}
export default TableDesign
export default withRouter(TableDesign)