king
2022-08-19 3b103caa6bfc9ed410e67156c3ca1785bf1cecc9
src/components/tabview/index.jsx
@@ -1,180 +1,79 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import {Tabs, Icon, Button, ConfigProvider, message, BackTop} from 'antd'
import {modifyTabview, toggleIsiframe} from '@/store/action'
// import asyncComponent from '@/utils/asyncComponent'
import asyncComponent from '@/utils/asyncLoadComponent'
import NotFount from '@/components/404'
import enUS from 'antd/es/locale/en_US'
import zhCN from 'antd/es/locale/zh_CN'
import mzhCN from '@/locales/zh-CN/main.js'
import menUS from '@/locales/en-US/main.js'
import { fromJS } from 'immutable'
import {Tabs, BackTop, notification} from 'antd'
import { RedoOutlined, CloseOutlined } from '@ant-design/icons'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { initActionPermission } from '@/store/action'
import asyncComponent from '@/utils/asyncLoadComponent'
import NotFount from '@/components/404'
import options from '@/store/options.js'
import MKEmitter from '@/utils/events.js'
import Api from '@/api'
import './index.scss'
const Home = asyncComponent(() => import('@/tabviews/home'))
const CustomPage = asyncComponent(() => import('@/tabviews/custom'))
const CommonTable = asyncComponent(() => import('@/tabviews/commontable'))
// const BaseTable = asyncComponent(() => import('@/tabviews/basetable'))
const CalendarPage = asyncComponent(() => import('@/tabviews/calendar'))
const TreePage = asyncComponent(() => import('@/tabviews/treepage'))
const VerupTable = asyncComponent(() => import('@/tabviews/verupmanage'))
const ScriptTable = asyncComponent(() => import('@/tabviews/scriptmanage'))
const TabManage = asyncComponent(() => import('@/tabviews/tabmanage'))
const Iframe = asyncComponent(() => import('@/tabviews/iframe'))
const RoleManage = asyncComponent(() => import('@/tabviews/rolemanage'))
const FormTab = asyncComponent(() => import('@/tabviews/formtab'))
let Comps = {}
let service = window.GLOB.service ? (/\/$/.test(window.GLOB.service) ? window.GLOB.service : window.GLOB.service + '/') : ''
let service = ''
if (process.env.NODE_ENV === 'production') {
  service = document.location.origin + '/' + service + 'zh-CN/'
  service = document.location.origin + '/' + window.GLOB.service + 'zh-CN/'
} else {
  service = 'http://qingqiumarket.cn/' + service + 'zh-CN/'
  service = window.GLOB.location + '/' + window.GLOB.service + 'zh-CN/'
}
class Header extends Component {
class TabViews extends Component {
  static propTpyes = {
    collapse: PropTypes.bool,
    tabviews: PropTypes.array // 标签页数组
    collapse: PropTypes.bool
  }
  state = {
    activeId: '',
    tabviews: null, // 标签集
    iFrameHeight: 0,
    dict: (!sessionStorage.getItem('lang') || sessionStorage.getItem('lang') === 'zh-CN') ? mzhCN : menUS,
    locale: (!sessionStorage.getItem('lang') || sessionStorage.getItem('lang') === 'zh-CN') ? zhCN : enUS
  }
  handleTabview (e, menu) {
    e.stopPropagation()
    // 关闭tab页,重新选择显示页
    let tabs = JSON.parse(JSON.stringify(this.state.tabviews))
    tabs = tabs.filter(tab => {
      return tab.MenuID !== menu.MenuID
  // 关闭tab页,重新选择显示页
  closeTabView = (id) => {
    let tabs = fromJS(this.state.tabviews).toJS()
    let index = -1
    tabs = tabs.filter((tab, i) => {
      if (tab.MenuID === id) {
        index = i
        return false
      } else {
        return true
      }
    })
    
    if (menu.selected) {
      tabs[0] && (tabs[0].selected = true)
    }
    this.props.modifyTabview(tabs)
  }
  changeTab (e, menu) {
    e.stopPropagation()
    // 窗口切换
    let tabs = JSON.parse(JSON.stringify(this.state.tabviews))
    tabs = tabs.map(tab => {
      tab.selected = false
      if (tab.MenuID === menu.MenuID) {
        tab.selected = true
    if (index > -1) {
      let activeId = ''
      if (id !== this.state.activeId) {
        activeId = this.state.activeId
      } else if (index > 0) {
        activeId = tabs[index - 1].MenuID || ''
      } else if (tabs[index]) {
        activeId = tabs[index].MenuID || ''
      }
      return tab
    })
    this.setState({
      tabviews: tabs
    })
    this.props.modifyTabview(tabs)
  }
  selectcomponent (view) {
    // 根据tab页中菜单信息,选择所需的组件
    if (view.type === 'Home') {
      return (<Comps.Home MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'CommonTable') {
      return (<Comps.CommonTable MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'DataManage') {
      return (<Comps.DataManage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'RolePermission') {
      return (<Comps.RoleManage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'TabForm') {
      return (<Comps.TabForm MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'FormTab') {
      return (<Comps.FormTab MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'iframe') {
      return (<Comps.Iframe key={view.MenuID} title={view.MenuName} MenuName={view.MenuName} url={service + view.LinkUrl}/>)
    } else {
      return (<NotFount key={view.MenuID} />)
    }
  }
  resetWindow (view) {
    // 窗口在iframe与普通页面切换时,修改左侧菜单栏样式
    if (!view) return
    let _isiframe = this.props.isiframe
    if (view && view.type === 'iframe') {
      _isiframe = true
    } else {
      _isiframe = false
    }
    if (_isiframe !== this.props.isiframe) {
      this.props.toggleIsiframe(_isiframe)
    }
  }
  copyMenuNo = (e) => {
    e.stopPropagation()
    let oInput = document.createElement('input')
    oInput.value = e.target.dataset.menuno || ''
    document.body.appendChild(oInput)
    oInput.select()
    document.execCommand('Copy')
    oInput.className = 'oInput'
    oInput.style.display = 'none'
    message.success(this.state.dict['main.copy.success'])
  }
  UNSAFE_componentWillMount () {
    if (!sessionStorage.getItem('lang') || sessionStorage.getItem('lang') === 'zh-CN') {
      moment.locale('zh-cn')
    } else {
      moment.locale('en')
    }
    this.setState({
      tabviews: this.props.tabviews
    })
  }
  componentDidMount () {
    let home = {
      MenuID: '1576117946681plembmkk9akkv8sn0vtdfdsfaf',
      MenuName: '首页',
      MenuNo: 'MESOrderDetailMwe',
      PageParam: {},
      id: 1,
      selected: true,
      src: '',
      text: '首页',
      type: 'Home'
    }
    this.props.modifyTabview([home])
  }
  UNSAFE_componentWillReceiveProps (nextProps) {
    if (nextProps.tabviews && !is(fromJS(this.state.tabviews), fromJS(nextProps.tabviews))) {
      // tab窗口页增加或删除
      if (nextProps.tabviews.length > this.state.tabviews.length) {
        // 查看新tab页需要组件是否加载
        let MenuIDs = this.state.tabviews.map(tab => {return tab.MenuID})
        let newtab = nextProps.tabviews.filter(tab => !MenuIDs.includes(tab.MenuID))[0]
        if (!Comps.Home && newtab.type === 'Home') {
          Comps.Home = asyncComponent(() => import('@/tabviews/home'))
        } else if (!Comps.CommonTable && newtab.type === 'CommonTable') {
          Comps.CommonTable = asyncComponent(() => import('@/tabviews/commontable'))
        } else if (!Comps.Iframe && newtab.type === 'iframe') {
          Comps.Iframe = asyncComponent(() => import('@/tabviews/iframe'))
        } else if (!Comps.DataManage && newtab.type === 'DataManage') {
          Comps.DataManage = asyncComponent(() => import('@/tabviews/datamanage'))
        } else if (!Comps.RoleManage && newtab.type === 'RolePermission') {
          Comps.RoleManage = asyncComponent(() => import('@/tabviews/rolemanage'))
        } else if (!Comps.TabForm && newtab.type === 'TabForm') {
          Comps.TabForm = asyncComponent(() => import('@/tabviews/tabform'))
        } else if (!Comps.TabForm && newtab.type === 'FormTab') {
          Comps.FormTab = asyncComponent(() => import('@/tabviews/formtab'))
        }
      }
      // 保存修改标签集
      this.setState({
        tabviews: nextProps.tabviews
        activeId,
        tabviews: tabs
      })
      let node = document.getElementById('root').parentNode.parentNode
@@ -184,60 +83,231 @@
    }
  }
  // shouldComponentUpdate(nextProps, nextState) {
  //   return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  // }
  refreshTabview = (e, menu) => {
    e.stopPropagation()
    window.GLOB.CacheMap = new Map()
    if (options.sysType === 'local' && window.GLOB.systemType !== 'production') {
      let roledefer = new Promise(resolve => {
        Api.getSystemConfig({
          func: 's_Get_TrdMenu_Role',
          edition_type: 'A',
          pro_sys: ''
        }).then(result => {
          if (!result) return
          if (!result.status) {
            notification.error({
              top: 92,
              message: result.message,
              duration: 10
            })
          } else {
            let _permAction = {loaded: true} // 按钮权限
            if (result.UserRoles_Menu) {
              result.UserRoles_Menu.forEach(menu => {
                if (!menu.MenuID) return
                _permAction[menu.MenuID] = true
              })
            }
            this.props.initActionPermission(_permAction)
          }
          resolve()
        })
      })
      // 获取主菜单参数
      let menudefer = new Promise(resolve => {
        Api.getAppVersion().then(() => {
          resolve()
        }, () => {
          resolve()
        })
      })
      Promise.all([roledefer, menudefer]).then(() => {
        MKEmitter.emit('reloadMenuView', menu.MenuID)
      })
    } else {
      MKEmitter.emit('reloadMenuView', menu.MenuID)
    }
  }
  modifyTabs = (tab, type, fixed) => {
    const { tabviews, activeId } = this.state
    if (type === 'plus' && fixed) {
      let _tabs = tabviews.filter(item => item.MenuID !== tab.MenuID)
      let index = _tabs.findIndex(item => item.MenuID === activeId)
      this.setState({
        tabviews: _tabs
      }, () => {
        if (index > -1) {
          _tabs.splice(index + 1, 0, tab)
        } else {
          _tabs.push(tab)
        }
        this.setState({
          tabviews: _tabs,
          activeId: tab.MenuID
        })
      })
    } else if (type === 'plus') {
      if (tabviews.findIndex(item => item.MenuID === tab.MenuID) > -1) {
        let _tabs = tabviews.filter(item => item.MenuID !== tab.MenuID)
        this.setState({
          tabviews: _tabs
        }, () => {
          this.setState({
            tabviews: [..._tabs, tab],
            activeId: tab.MenuID
          })
        })
      } else {
        this.setState({
          tabviews: [...tabviews, tab],
          activeId: tab.MenuID
        })
      }
    } else if (type === 'replace') {
      this.setState({
        tabviews: tab ? [tab] : [],
        activeId: tab ? tab.MenuID : ''
      })
    }
    let node = document.getElementById('root').parentNode.parentNode
    if (node) {
      node.scrollTop = 0
    }
  }
  changeTab = (e, menu) => {
    e.stopPropagation()
    // 窗口切换
    this.setState({
      activeId: menu.MenuID || ''
    }, () => {
      MKEmitter.emit('resetActiveMenu', menu.MenuID || '')
    })
  }
  selectcomponent = (view) => {
    // 根据tab页中菜单信息,选择所需的组件
    if (view.type === 'Home') {
      return (<Home MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'CommonTable' || view.type === 'ManageTable') {
      return (<CommonTable MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    // } else if (view.type === 'BaseTable') {
    //   return (<BaseTable MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'CustomPage') {
      return (<CustomPage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'TreePage') {
      return (<TreePage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'CalendarPage') {
      return (<CalendarPage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'VerupTable') {
      return (<VerupTable MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'ScriptTable') {
      return (<ScriptTable MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'TabManage') {
      return (<TabManage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'RolePermission') {
      return (<RoleManage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'appRolePermission') {
      return (<RoleManage MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID}/>)
    } else if (view.type === 'FormTab') {
      return (<FormTab MenuNo={view.MenuNo} MenuID={view.MenuID} MenuName={view.MenuName} key={view.MenuID} param={view.param}/>)
    } else if (view.type === 'iframe') {
      return (<Iframe key={view.MenuID} MenuID={view.MenuID} MenuNo={view.MenuNo} title={view.MenuName} MenuName={view.MenuName} url={service + view.LinkUrl}/>)
    } else {
      return (<NotFount key={view.MenuID} />)
    }
  }
  UNSAFE_componentWillMount () {
    if (!sessionStorage.getItem('lang') || sessionStorage.getItem('lang') === 'zh-CN') {
      moment.locale('zh-cn')
    } else {
      moment.locale('en')
    }
    if (sessionStorage.getItem('isEditState') !== 'true') {
      this.setState({
        activeId: 'home_page_id',
        tabviews: [{
          MenuID: 'home_page_id',
          MenuName: '首页',
          type: 'Home'
        }]
      })
    } else {
      this.setState({
        activeId: '',
        tabviews: []
      })
    }
  }
  componentDidMount () {
    MKEmitter.addListener('modifyTabs', this.modifyTabs)
    MKEmitter.addListener('closeTabView', this.closeTabView)
  }
  /**
   * @description 组件销毁,清除state更新
   */
  componentWillUnmount () {
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('modifyTabs', this.modifyTabs)
    MKEmitter.removeListener('closeTabView', this.closeTabView)
  }
  render () {
    const { tabviews } = this.state
    let view = tabviews.filter(tab => tab.selected)[0]
    this.resetWindow(view)
    let selectedTabId = view ? view.MenuID : ''
    const { tabviews, activeId } = this.state
    return (
      <section className={'flex-container content-box' + (this.props.collapse ? ' collapsed' : '')}>
        <ConfigProvider locale={this.state.locale}>
          <div className="content-header">
            {tabviews && tabviews.length > 0 &&
              <Tabs activeKey={selectedTabId}>
                {tabviews.map(view => {
                  return (
                    <Tabs.TabPane
                      className="test"
                      tab={
                        <span className="tab-control">
                          <span className="tab-name" onClick={(e) => {this.changeTab(e, view)}}>
                            {view.MenuName}
                          </span>
                          {view.type !== 'Home' ? <Icon type="close" onClick={(e) => {this.handleTabview(e, view)}}/> : null}
      <section id="mk-tabview-wrap" className={'mk-tabview-wrap' + (this.props.collapse ? ' collapsed' : '') + (tabviews && tabviews.length > 0 ? ' hastab' : '')}>
        <div className="content-header">
          {tabviews && tabviews.length > 0 &&
            <Tabs activeKey={activeId}>
              {tabviews.map((view, index) => {
                return (
                  <Tabs.TabPane
                    tab={
                      <span className="tab-control">
                        <RedoOutlined onClick={(e) => {this.refreshTabview(e, view)}}/>
                        <span className="tab-name" onClick={(e) => {this.changeTab(e, view)}}>
                          {view.MenuName}
                        </span>
                      }
                      key={view.MenuID}
                    >
                      {this.selectcomponent(view)}
                      {view.type !== 'CommonTable' ?
                        <Button
                          icon="copy"
                          shape="circle"
                          className={'main-copy ' + (view.type === 'iframe' ? 'ifr-copy' : '')}
                          data-menuno={view.MenuNo}
                          onClick={this.copyMenuNo}
                        /> : null
                      }
                      <BackTop>
                        <div className="ant-back-top">
                          <div className="ant-back-top-content">
                            <div className="ant-back-top-icon"></div>
                          </div>
                        {view.type !== 'Home' ?
                          <CloseOutlined onClick={(e) => {e.stopPropagation();this.closeTabView(view.MenuID)}}/> : null
                        }
                      </span>
                    }
                    key={view.MenuID}
                  >
                    {this.selectcomponent(view)}
                    <BackTop>
                      <div className="ant-back-top">
                        <div className="ant-back-top-content">
                          <div className="ant-back-top-icon"></div>
                        </div>
                      </BackTop>
                    </Tabs.TabPane>
                  )
                })}
              </Tabs>
            }
          </div>
        </ConfigProvider>
                      </div>
                    </BackTop>
                    {/* {options.sysType === 'local' && window.GLOB.systemType !== 'production' ? <div className="mk-water-mark">测试系统</div> : null} */}
                  </Tabs.TabPane>
                )
              })}
            </Tabs>
          }
        </div>
      </section>
    )
  }
@@ -245,17 +315,14 @@
const mapStateToProps = (state) => {
  return {
    tabviews: state.tabviews,
    collapse: state.collapse,
    isiframe: state.isiframe
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    modifyTabview: (tabviews) => dispatch(modifyTabview(tabviews)),
    toggleIsiframe: (isiframe) => dispatch(toggleIsiframe(isiframe))
    initActionPermission: (permAction) => dispatch(initActionPermission(permAction))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Header)
export default connect(mapStateToProps, mapDispatchToProps)(TabViews)