king
2022-11-29 8b6f9a84e5eb704b25c105cce31904381bd81107
src/tabviews/zshare/actionList/excelInbutton/index.jsx
@@ -1,34 +1,68 @@
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { Button, Modal, notification, message } from 'antd'
import ExcelIn from './excelin'
import Utils from '@/utils/utils.js'
import Utils, { getExcelInSql } from '@/utils/utils.js'
import options from '@/store/options.js'
import Api from '@/api'
import zhCN from '@/locales/zh-CN/main.js'
import enUS from '@/locales/en-US/main.js'
import MKEmitter from '@/utils/events.js'
import './index.scss'
import MkIcon from '@/components/mk-icon'
// import './index.scss'
const { confirm } = Modal
class ExcelInButton extends Component {
  static propTpyes = {
    show: PropTypes.any,              // 显示样式
    BID: PropTypes.string,            // 主表ID
    BData: PropTypes.any,             // 主表数据
    selectedData: PropTypes.any,      // 子表中选择数据
    Tab: PropTypes.any,               // 如果当前元素为标签时,tab为标签信息
    btn: PropTypes.object,            // 按钮
    setting: PropTypes.any,           // 页面通用设置
    updateStatus: PropTypes.func,     // 按钮状态更新
    disabled: PropTypes.any,          // 行按钮禁用
  }
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    loading: false,
    selines: null,
    disabled: false,
    hidden: false,
    primaryId: '',
  }
  UNSAFE_componentWillMount () {
    const { btn, selectedData, BData } = this.props
    let disabled = false
    if (btn.controlField && selectedData && selectedData.length > 0) { // 表格中按钮隐藏控制
      selectedData.forEach(item => {
        let s = item[btn.controlField] !== undefined ? item[btn.controlField] + '' : ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          disabled = true
        }
      })
      this.setState({hidden: disabled && btn.control === 'hidden'})
    } else if (btn.control === 'parent') {
      if (!BData || !BData.hasOwnProperty(btn.controlField)) {
        this.setState({hidden: true})
      } else {
        let s = BData[btn.controlField] + ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          this.setState({hidden: true})
        } else {
          this.setState({hidden: false})
        }
      }
    }
    if (this.props.disabled || disabled) {
      this.setState({disabled: true})
    }
  }
  shouldComponentUpdate (nextProps, nextState) {
@@ -36,10 +70,40 @@
  }
  componentDidMount () {
    const { show } = this.props
    MKEmitter.addListener('triggerBtnId', this.actionTrigger)
  }
    if (show === 'actionList') {
      MKEmitter.addListener('triggerBtnId', this.actionTrigger)
  UNSAFE_componentWillReceiveProps (nextProps) {
    const { btn, selectedData, BData } = this.props
    let disabled = false
    if (btn.controlField && !is(fromJS(nextProps.selectedData || []), fromJS(selectedData || []))) {
      if (nextProps.selectedData && nextProps.selectedData.length > 0) { // 表格中按钮隐藏控制
        nextProps.selectedData.forEach(item => {
          let s = item[btn.controlField] !== undefined ? item[btn.controlField] + '' : ''
          if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
            disabled = true
          }
        })
      }
      this.setState({disabled, hidden: disabled && btn.control === 'hidden'})
    } else if (btn.control === 'parent' && !is(fromJS(nextProps.BData || {}), fromJS(BData || {}))) {
      if (!nextProps.BData || !nextProps.BData.hasOwnProperty(btn.controlField)) {
        this.setState({hidden: true})
      } else {
        let s = nextProps.BData[btn.controlField] + ''
        if (s === btn.controlVal || (btn.controlVal && btn.controlVal.split(',').includes(s))) {
          this.setState({hidden: true})
        } else {
          this.setState({hidden: false})
        }
      }
    }
    if (nextProps.disabled || disabled) {
      this.setState({disabled: true})
    } else {
      this.setState({disabled: false})
    }
  }
@@ -49,41 +113,29 @@
    }
    MKEmitter.removeListener('triggerBtnId', this.actionTrigger)
  }
  /**
   * @description 按钮状态改变
   */
  updateStatus = (type) => {
    if (type === 'start') {
      this.setState({
        loading: true
      })
    } else if (type === 'over') {
      this.setState({
        loading: false
      })
    }
  }
  
  /**
   * @description 触发按钮操作
   */
  actionTrigger = (triggerId) => {
    const { setting, Tab, BID, btn, selectedData } = this.props
    const { loading } = this.state
  actionTrigger = (triggerId, record, type) => {
    const { setting, BID, btn, selectedData } = this.props
    const { loading, disabled } = this.state
    if ((triggerId && btn.uuid !== triggerId) || loading) return
    if (loading || disabled) return
    if (triggerId && btn.uuid !== triggerId) return
    if (Tab && Tab.supMenu && !BID) {
    if (setting.supModule && !BID) {
      notification.warning({
        top: 92,
        message: '需要上级主键值!',
        duration: 5
      })
      return
    } else if (type === 'linkbtn' && !btn.$toolbtn && !is(fromJS(selectedData || []), fromJS(record))) {
      return
    }
    let data = selectedData || []
    let data = record || selectedData || []
    
    if (btn.Ot === 'requiredSgl' && data.length !== 1) {
      // 需要选择单行时,校验数据
@@ -93,25 +145,29 @@
        duration: 5
      })
      return
    }
    if (btn.verify && btn.verify.sheet && btn.verify.columns && btn.verify.columns.length > 0) {
      let primaryId = '' // 导入时行Id
      if (btn.Ot === 'requiredSgl') {
        primaryId = data[0][setting.primaryKey] || ''
      }
      this.setState({
        primaryId: primaryId
      }, () => {
        this.refs.excelIn.exceltrigger()
      })
    } else {
    } else if (!btn.verify || !btn.verify.sheet || !btn.verify.columns || btn.verify.columns.length === 0) {
      notification.warning({
        top: 92,
        message: 'excel导入验证信息未设置!',
        duration: 5
      })
      return
    }
    let primaryId = '' // 导入时行Id
    if (btn.Ot === 'requiredSgl' && setting.primaryKey) {
      primaryId = data[0][setting.primaryKey] || ''
    }
    this.setState({
      selines: data,
      primaryId: primaryId
    }, () => {
      this.refs.excelIn.exceltrigger()
    })
    if (window.GLOB.systemType === 'production') {
      MKEmitter.emit('queryTrigger', {menuId: btn.uuid, name: '导入Excel'})
    }
  }
@@ -126,7 +182,7 @@
  execSuccess = (res) => {
    const { btn } = this.props
    if (res && res.ErrCode === 'S') { // 执行成功
    if (res && (res.ErrCode === 'S' || !res.ErrCode)) { // 执行成功
      notification.success({
        top: 92,
        message: res.ErrMesg || this.state.dict['main.action.confirm.success'],
@@ -144,7 +200,19 @@
      loading: false
    })
    this.props.updateStatus('refresh', btn.execSuccess)
    if (btn.execSuccess === 'closepoptab') {
      MKEmitter.emit('popclose')
    } else if (btn.execSuccess !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execSuccess, btn, '', this.state.selines)
    }
    btn.syncComponentId && MKEmitter.emit('reloadData', btn.syncComponentId)
    if (btn.switchTab && btn.switchTab.length > 0) {
      let id = btn.switchTab[btn.switchTab.length - 1]
      let node = document.getElementById('tab' + id)
      node && node.click()
    }
  }
  /**
@@ -181,13 +249,17 @@
      loading: false
    })
    this.props.updateStatus('refresh', btn.execError)
    if (btn.execError === 'closepoptab') {
      MKEmitter.emit('popclose')
    } else if (btn.execError !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execError, btn, '', this.state.selines)
    }
  }
  /**
   * @description Excel 导入
   */
  getexceldata = (data, errors, sheetName) => {
  getexceldata = (data, errors, sheetName, errDetail) => {
    const { btn } = this.props
    if (errors) {
@@ -206,12 +278,12 @@
      } else if (errors === 'headerError') {
        notification.warning({
          top: 92,
          message: '工作表《' + sheetName + '》表头设置错误,请检查表头中的名称及顺序,与按钮Excel列信息是否一致!',
          message: `工作表《${sheetName}》表头错误,${errDetail}`,
          duration: 5
        })
      }
      this.updateStatus('over')
      this.setState({ loading: false })
      return
    }
@@ -221,7 +293,7 @@
        message: '未获取到工作表《' + sheetName + '》数据!',
        duration: 5
      })
      this.updateStatus('over')
      this.setState({ loading: false })
      return
    } else if (data.length * btn.verify.columns.length > 30000) {
      notification.warning({
@@ -231,7 +303,7 @@
      })
    }
    let result = Utils.getExcelInSql(btn, data, this.state.dict, (this.props.BID || ''))
    let result = getExcelInSql(btn, data, this.state.dict, (this.props.BID || ''))
    if (result.errors) {
      notification.warning({
@@ -239,7 +311,7 @@
        message: result.errors,
        duration: 5
      })
      this.updateStatus('over')
      this.setState({ loading: false })
      return
    }
@@ -255,7 +327,7 @@
    if (btn.intertype === 'system') { // 系统存储过程
      param.func = 'sPC_TableData_InUpDe'
      
      if (this.props.dataManager) { // 数据权限
      if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
        result.sql = result.sql.replace(/\$@/ig, '/*')
        result.sql = result.sql.replace(/@\$/ig, '*/')
        result.bottom = result.bottom.replace(/\$@/ig, '/*')
@@ -267,23 +339,86 @@
      
      param.excel_in_type = 'true'
      param.LText1 = Utils.formatOptions(result.insert)
      param.LText2 = Utils.formatOptions(result.bottom)
      param.LText = Utils.formatOptions(result.sql)
      param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
      param.LText2 = result.bottom
      param.LText = result.sql
      let unCheckParam = null
      if (/\$check@|@check\$/ig.test(param.LText2) || /\$check@|@check\$/ig.test(param.LText)) {
        unCheckParam = fromJS(param).toJS()
        param.LText = param.LText.replace(/\$check@|@check\$/ig, '')
        param.LText2 = param.LText2.replace(/\$check@|@check\$/ig, '')
      }
      param.LText2 = Utils.formatOptions(param.LText2)
      param.LText = Utils.formatOptions(param.LText)
      param.secretkey = Utils.encrypt(param.LText, param.timestamp)
      if (this.props.menuType === 'HS' && param.timestamp) { // 云端验证
      if (window.GLOB.mkHS && param.timestamp) { // 云端验证
        param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
      }
      Api.genericInterface(param).then((res) => {
        if (res.status) {
          this.execSuccess(res)
        } else {
          this.execError(res)
      param.menuname = btn.logLabel
      if (window.GLOB.probation) {
        param.s_debug_type = 'Y'
      }
      if (unCheckParam) {
        unCheckParam.LText = unCheckParam.LText.replace(/\$check@/ig, '/*').replace(/@check\$/ig, '*/')
        unCheckParam.LText = Utils.formatOptions(unCheckParam.LText)
        unCheckParam.LText2 = unCheckParam.LText2.replace(/\$check@/ig, '/*').replace(/@check\$/ig, '*/')
        unCheckParam.LText2 = Utils.formatOptions(unCheckParam.LText2)
        unCheckParam.secretkey = Utils.encrypt(unCheckParam.LText, unCheckParam.timestamp)
        unCheckParam.menuname = btn.logLabel
        if (window.GLOB.probation) {
          unCheckParam.s_debug_type = 'Y'
        }
      }, () => {
        this.execError({})
      })
        Api.genericInterface(param).then(res => {
          if (res.status) {
            this.execSuccess(res)
          } else if (res.ErrCode === 'C') {
            const _this = this
            confirm({
              title: '继续执行?',
              content: res.message,
              onOk() {
                return new Promise(resolve => {
                  Api.genericInterface(unCheckParam).then(result => {
                    if (result.status) {
                      _this.execSuccess(result)
                    } else {
                      _this.execError(result)
                    }
                    resolve()
                  })
                })
              },
              onCancel() {
                _this.execError(res)
              }
            })
          } else {
            this.execError(res)
          }
        }, () => {
          this.execError({})
        })
      } else {
        Api.genericInterface(param).then((res) => {
          if (res.status) {
            this.execSuccess(res)
          } else {
            this.execError(res)
          }
        }, () => {
          this.execError({})
        })
      }
    } else if (btn.intertype === 'inner' && btn.innerFunc) { // 自定义存储过程
      param.func = btn.innerFunc
@@ -332,17 +467,39 @@
        // 外部请求
        _outParam = fromJS(res).toJS()
        if (this.props.menuType === 'HS') {
        if (window.GLOB.mkHS) {
          if (btn.sysInterface === 'true' && options.cloudServiceApi) {
            param.rduri = options.cloudServiceApi
            param.userid = sessionStorage.getItem('CloudUserID') || ''
            param.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
          } else if (btn.sysInterface !== 'true') {
            param.rduri = btn.interface
            if (window.GLOB.systemType === 'production' && btn.proInterface) {
              param.rduri = btn.proInterface
            } else {
              param.rduri = btn.interface
            }
          }
        } else {
          if (btn.sysInterface === 'true' && window.GLOB.mainSystemApi) {
            param.rduri = window.GLOB.mainSystemApi
          } else if (btn.sysInterface !== 'true') {
            param.rduri = btn.interface
          if (btn.sysInterface === 'true') {
            if (window.GLOB.mainSystemApi) {
              param.rduri = window.GLOB.mainSystemApi
            }
          } else if (btn.sysInterface === 'external') {
            if (window.GLOB.systemType === 'production') {
              param.$token = btn.exProInterface || ''
            } else {
              param.$token = btn.exInterface || ''
            }
          } else {
            if (window.GLOB.systemType === 'production' && btn.proInterface) {
              param.rduri = btn.proInterface
            } else {
              param.rduri = btn.interface
            }
            let host = window.GLOB.baseurl.replace(/http(s):\/\//, '')
            if (param.rduri.indexOf(host) === -1 && /\/dostars/.test(param.rduri)) {
              param.$login = true
            }
          }
        }
@@ -350,7 +507,7 @@
          res.func = btn.outerFunc
        }
        
        if (this.props.menuType === 'HS' && res.func === 's_sDataDictb_excelIn') { // s_sDataDictb_excelIn 云端验证
        if (window.GLOB.mkHS && res.func === 's_sDataDictb_excelIn') { // s_sDataDictb_excelIn 云端验证
          param.LText = Utils.formatOptions(result.sql)
          param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
          param.secretkey = Utils.encrypt(param.LText, param.timestamp)
@@ -390,42 +547,49 @@
  }
  render() {
    const { btn, show } = this.props
    const { loading } = this.state
    const { btn } = this.props
    const { loading, disabled, hidden } = this.state
    if (show === 'actionList') {
      return <div style={{display: 'inline-block'}}>
        <Button
          icon={btn.icon}
          loading={loading}
          className={'mk-btn mk-' + btn.class}
          onClick={() => {this.actionTrigger()}}
        >{btn.label}</Button>
        <ExcelIn btn={btn} triggerExcelIn={() => this.updateStatus('start')} returndata={this.getexceldata} ref="excelIn" />
      </div>
    } else { // icon、text、 all 卡片
      return <div style={{display: 'inline-block'}}>
        <Button
          type="link"
          loading={loading}
          icon={show === 'text' ? '' : (show === 'icon' ? (btn.icon || 'upload') : (btn.icon || ''))}
          onClick={() => {this.actionTrigger()}}
        >{show === 'icon' ? '' : btn.label}</Button>
        <ExcelIn btn={btn} triggerExcelIn={() => this.updateStatus('start')} returndata={this.getexceldata} ref="excelIn" />
      </div>
    if (hidden) return null
    let label = ''
    let icon = ''
    let type = 'link'
    let className = ''
    if (btn.show === 'button') {
      label = btn.label
      icon = btn.icon || ''
    } else if (btn.show === 'link') {
      label = <span>{btn.label}{btn.icon ? <MkIcon style={{marginLeft: '8px'}} type={btn.icon}/> : ''}</span>
      icon = ''
    } else if (btn.show === 'icon') {
      icon = btn.icon || 'upload'
    } else if (!btn.$toolbtn) {
      icon = btn.icon || ''
      label = btn.label
      className = 'mk-btn mk-' + btn.class
    } else {
      type = ''
      icon = btn.icon || ''
      label = btn.label
      className = 'mk-btn mk-' + btn.class
    }
    return <>
      <Button
        type={type}
        title={disabled ? (btn.reason || '') : (btn.show === 'icon' ? btn.label : '')}
        loading={loading}
        disabled={disabled}
        style={btn.style}
        icon={icon}
        className={className}
        onClick={(e) => {e.stopPropagation(); this.actionTrigger()}}
      >{label}</Button>
      <ExcelIn btn={btn} triggerExcelIn={() => this.setState({ loading: true })} returndata={this.getexceldata} ref="excelIn" />
    </>
  }
}
const mapStateToProps = (state) => {
  return {
    menuType: state.editLevel,
    dataManager: state.dataManager
  }
}
const mapDispatchToProps = () => {
  return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(ExcelInButton)
export default ExcelInButton