king
2021-09-01 31ec63f0419895876cbaba99637a884a32d33d0d
src/tabviews/zshare/actionList/exceloutbutton/index.jsx
@@ -3,7 +3,7 @@
import moment from 'moment'
import {connect} from 'react-redux'
import { is, fromJS } from 'immutable'
import { Button, Modal, notification, message } from 'antd'
import { Button, Modal, notification, message, Icon } from 'antd'
import * as XLSX from 'xlsx'
import Utils from '@/utils/utils.js'
@@ -11,38 +11,46 @@
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'
class ExcelOutButton extends Component {
  static propTpyes = {
    BID: PropTypes.string,            // 主表ID
    position: PropTypes.any,          // 按钮位置,工具栏为toolbar
    show: PropTypes.any,              // 显示样式
    Tab: PropTypes.any,               // 如果当前元素为标签时,tab为标签信息
    btn: PropTypes.object,            // 按钮
    setting: PropTypes.any,           // 页面通用设置
    updateStatus: PropTypes.func,     // 按钮状态更新
    getexceloutparam: PropTypes.func, // 获取表格中参数
    triggerBtn: PropTypes.any,
  }
  state = {
    dict: sessionStorage.getItem('lang') !== 'en-US' ? zhCN : enUS,
    excelName: '',
    excelName: '',  // 文件名
    search: '',     // 搜索条件
    loading: false
  }
  /**
   * @description 外部触发按钮点击
   */
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.triggerBtn && !is(fromJS(this.props.triggerBtn), fromJS(nextProps.triggerBtn)) && nextProps.triggerBtn.button.uuid === this.props.btn.uuid) {
      this.actionTrigger()
    }
    loading: false  // 导出中
  }
  shouldComponentUpdate (nextProps, nextState) {
    return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState))
  }
  componentDidMount () {
    const { position } = this.props
    if (position === 'toolbar') {
      MKEmitter.addListener('triggerBtnId', this.actionTrigger)
    }
    MKEmitter.addListener('returnModuleParam', this.triggerExcelout)
  }
  componentWillUnmount () {
    this.setState = () => {
      return
    }
    MKEmitter.removeListener('triggerBtnId', this.actionTrigger)
    MKEmitter.removeListener('returnModuleParam', this.triggerExcelout)
  }
  /**
@@ -54,22 +62,23 @@
        loading: true,
        excelName: name
      })
      this.props.updateStatus('start')
    } else if (type === 'over') {
      this.setState({
        loading: false
      })
      this.props.updateStatus('over')
    }
  }
  
  /**
   * @description 触发按钮操作
   */
  actionTrigger = () => {
  actionTrigger = (triggerId) => {
    const { setting, Tab, BID, btn } = this.props
    const { loading } = this.state
    if (Tab && Tab.supMenu && !BID) {
    if ((triggerId && btn.uuid !== triggerId) || loading) return
    if (((Tab && Tab.supMenu) || setting.supModule) && !BID) {
      notification.warning({
        top: 92,
        message: '需要上级主键值!',
@@ -78,10 +87,14 @@
      return
    }
    if (
      btn.intertype === 'inner' && !btn.innerFunc &&
      ((setting.interType === 'inner' && setting.innerFunc) || setting.interType === 'outer')
    ) {
    if (btn.intertype === 'system' && setting.interType !== 'system') {
      notification.warning({
        top: 92,
        message: '导出按钮配置错误!',
        duration: 5
      })
      return
    } else if (btn.intertype === 'inner' && !btn.innerFunc) {
      notification.warning({
        top: 92,
        message: '导出按钮配置错误!',
@@ -97,24 +110,27 @@
      return
    }
    this.triggerExcelout()
    MKEmitter.emit('queryModuleParam', btn.$menuId, btn.uuid)
    if (window.GLOB.systemType === 'production') {
      MKEmitter.emit('queryTrigger', {menuId: btn.uuid, name: '导出Excel'})
    }
  }
  /**
   * @description Excel 导出
   */
  triggerExcelout = () => {
  triggerExcelout = (menuId, btnId, viewParam) => {
    const { btn } = this.props
    let viewParam = this.props.getexceloutparam()
    if (btn.$menuId !== menuId || btn.uuid !== btnId || !viewParam) return
    let name = `${viewParam.menuName}${moment().format('YYYYMMDDHHmmss')}.xlsx`
    let pageSize = 1000
    if (btn.search === 'true' && viewParam.search && viewParam.search.length > 0) {
      let valid = false
      viewParam.search.forEach(item => {
        if (Array.isArray(item.value) && item.value.length > 0) {
          valid = true
        } else if (item.value || item.value === 0) {
        if (item.value || item.value === 0) {
          valid = true
        }
      })
@@ -129,21 +145,21 @@
      }
    }
    if (btn.intertype === 'inner' && !btn.innerFunc && !viewParam.arr_field) { // 使用系统函数
    if (btn.intertype === 'system' && !viewParam.arr_field) { // 使用系统函数
      notification.warning({
        top: 92,
        message: '未设置显示列!',
        duration: 5
      })
      return
    } else if (btn.intertype === 'inner' && !btn.innerFunc && btn.verify && btn.verify.enable === 'true') {
    } else if (btn.intertype === 'system' && btn.verify && btn.verify.enable === 'true') {
      this.setState({search: fromJS(viewParam.search).toJS()})
    }
    
    this.updateStatus('start', name)
    if (btn.pagination !== 'true') {
      if (btn.intertype === 'inner' && !btn.innerFunc) { // 使用系统函数
      if (btn.intertype === 'system') { // 使用系统函数
        let param = this.getExcelDefaultParam(viewParam.arr_field, viewParam.orderBy, viewParam.search)
        Api.genericInterface(param).then(result => {
@@ -155,7 +171,7 @@
        }, () => {
          this.execError({})
        })
      } else if (btn.intertype === 'inner' && btn.innerFunc) { // 使用内部函数
      } else if (btn.intertype === 'inner') { // 使用内部函数
        let param = this.getExcelCustomParam(viewParam.orderBy, viewParam.search)
        param.func = btn.innerFunc
@@ -175,13 +191,21 @@
          if (btn.sysInterface === 'true' && options.cloudServiceApi) {
            param.rduri = options.cloudServiceApi
          } 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 (window.GLOB.systemType === 'production' && btn.proInterface) {
              param.rduri = btn.proInterface
            } else {
              param.rduri = btn.interface
            }
          }
        }
  
@@ -213,13 +237,21 @@
              if (btn.sysInterface === 'true' && options.cloudServiceApi) {
                res.rduri = options.cloudServiceApi
              } else if (btn.sysInterface !== 'true') {
                res.rduri = btn.interface
                if (window.GLOB.systemType === 'production' && btn.proInterface) {
                  res.rduri = btn.proInterface
                } else {
                  res.rduri = btn.interface
                }
              }
            } else {
              if (btn.sysInterface === 'true' && window.GLOB.mainSystemApi) {
                res.rduri = window.GLOB.mainSystemApi
              } else if (btn.sysInterface !== 'true') {
                res.rduri = btn.interface
                if (window.GLOB.systemType === 'production' && btn.proInterface) {
                  res.rduri = btn.proInterface
                } else {
                  res.rduri = btn.interface
                }
              }
            }
  
@@ -274,13 +306,21 @@
          if (btn.sysInterface === 'true' && options.cloudServiceApi) {
            res.rduri = options.cloudServiceApi
          } else if (btn.sysInterface !== 'true') {
            res.rduri = btn.interface
            if (window.GLOB.systemType === 'production' && btn.proInterface) {
              res.rduri = btn.proInterface
            } else {
              res.rduri = btn.interface
            }
          }
        } else {
          if (btn.sysInterface === 'true' && window.GLOB.mainSystemApi) {
            res.rduri = window.GLOB.mainSystemApi
          } else if (btn.sysInterface !== 'true') {
            res.rduri = btn.interface
            if (window.GLOB.systemType === 'production' && btn.proInterface) {
              res.rduri = btn.proInterface
            } else {
              res.rduri = btn.interface
            }
          }
        }
@@ -320,14 +360,14 @@
  getExcelOutData = (viewParam, pageIndex, pageSize, data) => {
    const { btn } = this.props
    let param = null
    if (btn.intertype === 'inner' && !btn.innerFunc) { // 使用系统函数
    if (btn.intertype === 'system') { // 使用系统函数
      if (!viewParam.arr_field) {
        this.execError({ErrCode: 'N', message: '未设置显示列!'})
        return
      }
      param = this.getExcelDefaultParam(viewParam.arr_field, viewParam.orderBy, viewParam.search, true, pageIndex, pageSize)
    } else if (btn.intertype === 'inner' && btn.innerFunc) { // 使用内部函数
    } else if (btn.intertype === 'inner') { // 使用内部函数
      param = this.getExcelCustomParam(viewParam.orderBy, viewParam.search, true, pageIndex, pageSize)
      param.func = btn.innerFunc
@@ -338,13 +378,21 @@
        if (btn.sysInterface === 'true' && options.cloudServiceApi) {
          param.rduri = options.cloudServiceApi
        } 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 (window.GLOB.systemType === 'production' && btn.proInterface) {
            param.rduri = btn.proInterface
          } else {
            param.rduri = btn.interface
          }
        }
      }
      
@@ -378,56 +426,150 @@
   */
  exportExcel = (data) => {
    const { btn } = this.props
    if (data && data.length > 0) {
      try {
        let _header = []
        let _topRow = {}
        let colwidth = []
    try {
      let imgCol = btn.verify.columns.filter(col => col.type === 'image')[0]
        btn.verify.columns.forEach(col => {
          if (!data[0].hasOwnProperty(col.Column)) return
          if (_topRow[col.Column]) return
          _header.push(col.Column)
          _topRow[col.Column] = col.Text
          colwidth.push({width: col.Width})
      if (imgCol) {
        const column = btn.verify.columns.map(item => {
          let col = {
            title: item.Text,
            key: item.Column,
            type: 'text',
            width: (item.Width || 20) * 10
          }
          if (item.type === 'image') {
            col.type = 'image'
            col.height = col.width
          }
          return col
        })
        let table = []
        table.push(_topRow)
        data.forEach(item => {
        data && data.forEach((item, index) => {
          let _row = {}
          _header.forEach(field => {
            _row[field] = item[field]
          item.$Index = index + 1 + ''
          btn.verify.columns.forEach((col, i) => {
            if (item[col.Column] && col.abs === 'true') {
              _row[col.Column] = Math.abs(item[col.Column])
            } else {
              _row[col.Column] = item[col.Column]
            }
          })
          table.push(_row)
        })
        const ws = XLSX.utils.json_to_sheet(table, {header: _header, skipHeader: true})
        ws['!cols'] = colwidth
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        XLSX.writeFile(wb, this.state.excelName)
        this.table2excel(column, table, this.state.excelName.replace(/\.xlsx/ig, '.xls'))
        if (btn.verify && btn.verify.enable === 'true' && btn.verify.script) {
          this.execCustomScript()
        } else {
          this.execSuccess({ErrCode: 'S', ErrMesg: '导出成功!'})
        }
      } catch {
        this.execError({ErrCode: 'N', message: 'Excel生成失败!'})
      } else {
        let _header = []
        let _topRow = {}
        let colwidth = []
        let abses = []
        btn.verify.columns.forEach(col => {
          if (_topRow[col.Column]) return
          _header.push(col.Column)
          _topRow[col.Column] = col.Text
          if (col.abs === 'true') {
            abses.push(col.Column)
          }
          colwidth.push({width: col.Width || 20})
        })
        let table = []
        table.push(_topRow)
        data && data.forEach((item, index) => {
          let _row = {}
          item.$Index = index + 1 + ''
          _header.forEach(field => {
            if (item[field] && abses.includes(field)) {
              _row[field] = Math.abs(item[field])
            } else {
              _row[field] = item[field]
            }
          })
          table.push(_row)
        })
        const ws = XLSX.utils.json_to_sheet(table, {header: _header, skipHeader: true})
        ws['!cols'] = colwidth
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        XLSX.writeFile(wb, this.state.excelName)
        if (btn.verify && btn.verify.enable === 'true' && btn.verify.script) {
          this.execCustomScript()
        } else {
          this.execSuccess({ErrCode: 'S', ErrMesg: '导出成功!'})
        }
      }
    } else {
      this.execError({ErrCode: 'N', message: '未查询到导出数据!'})
    } catch (e) {
      this.execError({ErrCode: 'N', message: 'Excel生成失败!'})
    }
  }
  table2excel = (column, data, excelName) => {
    let thead = column.reduce((result, item) => {
      return result + `<th>${item.title}</th>`
    }, '')
    thead = `<thead><tr>${thead}</tr></thead>`
    let tbody = data.reduce((result, row) => {
      const temp = column.reduce((tds, col) => {
        let cell = '<td></td>'
        if (col.type !== 'image' || !row[col.key]) {
          cell = `<td style="width: ${col.width}px;">${row[col.key]}</td>`
        } else if (col.type === 'image') {
          cell = `<td style="width: ${col.width}px;height: ${col.height}px;"><img src="${row[col.key]}" width="${col.width * 0.75}"></td>`
        }
        return tds + cell
      }, '')
      return result + `<tr>${temp}</tr>`
    }, '')
    tbody = `<tbody>${tbody}</tbody>`
    const table = thead + tbody
    let html = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>"
    html += '<head><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'
    html += '<xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>Sheet1</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head>'
    html += `<body><table>${table}</table></body>`
    html += '</html>'
    let url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html)
    // let url = 'data:application/vnd.ms-excel;base64,' + window.btoa(unescape(encodeURIComponent(html)))
    let link = document.createElement('a')
    link.href = url
    link.download = excelName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
  /**
   * @description 执行自定义脚本
@@ -437,7 +579,7 @@
    const { search } = this.state
    let script = btn.verify.script
    if (this.props.dataManager) { // 数据权限
    if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
      script = script.replace(/\$@/ig, '/*')
      script = script.replace(/@\$/ig, '*/')
    } else {
@@ -457,24 +599,21 @@
    })
    let param = {
      func: 'sPC_TableData_InUpDe'
      func: 'sPC_TableData_InUpDe',
      menuname: btn.logLabel
    }
    if (this.props.BID) {
      param.BID = this.props.BID
    }
    let { LText, LText1, LText2 } = Utils.sPCInUpDeFormatOptions(script)
    param.LText2 = LText2
    param.LText1 = LText1
    param.LText = LText
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    param.exec_type = 'y' // 后台解码
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt('', param.timestamp)
    param.LText = Utils.formatOptions(param.LText)
    if (this.props.menuType === 'HS') { // 函数 sPC_TableData_InUpDe 云端验证
      param.open_key = Utils.encrypt(param.secretkey, param.timestamp, true)
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
    }
    Api.genericInterface(param).then((res) => {
@@ -500,7 +639,7 @@
    }
    // 数据管理权限
    if (this.props.dataManager) {
    if (sessionStorage.getItem('dataM') === 'true') {
      param.dataM = 'Y'
    }
@@ -520,7 +659,7 @@
   * @description 获取默认存储过程请求参数
   */
  getExcelDefaultParam = (arr_field, orderBy, search, pagination = false, pageIndex = 1, pageSize = 100) => {
    const { setting } = this.props
    const { setting, btn } = this.props
    let _search = Utils.joinMainSearchkey(search)
@@ -530,34 +669,33 @@
      func: 'sPC_Get_TableData',
      obj_name: 'data',
      arr_field: arr_field,
      custom_script: setting.customScript || '',
      default_sql: setting.default || 'true'
      custom_script: setting.customScript,
      default_sql: setting.default || 'true',
      menuname: btn.logLabel
    }
    // 数据管理权限
    if (this.props.dataManager) {
    if (sessionStorage.getItem('dataM') === 'true') {
      param.dataM = 'Y'
    }
    if (this.props.BID) {
      param.BID = this.props.BID
    }
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    let RoleID = sessionStorage.getItem('role_id') || ''
    let departmentcode = sessionStorage.getItem('departmentcode') || ''
    let organization = sessionStorage.getItem('organization') || ''
    let city = sessionStorage.getItem('city') || ''
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
    
    let _dataresource = setting.dataresource
    if (/\s/.test(_dataresource)) {
      _dataresource = '(' + _dataresource + ') tb'
    }
    if (this.props.dataManager) { // 数据权限
      _dataresource = _dataresource.replace(/\$@/ig, '/*')
      _dataresource = _dataresource.replace(/@\$/ig, '*/')
      param.custom_script = param.custom_script.replace(/\$@/ig, '/*')
      param.custom_script = param.custom_script.replace(/@\$/ig, '*/')
    } else {
      _dataresource = _dataresource.replace(/@\$|\$@/ig, '')
      param.custom_script = param.custom_script.replace(/@\$|\$@/ig, '')
    }
    let regoptions = null
    if (setting.queryType === 'statistics' || param.custom_script) {
@@ -571,6 +709,15 @@
      })
      regoptions.push({
        reg: new RegExp('@login_city@', 'ig'),
        value: city
      }, {
        reg: new RegExp('@userName@', 'ig'),
        value: userName
      }, {
        reg: new RegExp('@fullName@', 'ig'),
        value: fullName
      }, {
        reg: new RegExp('@orderBy@', 'ig'),
        value: orderBy
      }, {
@@ -598,6 +745,9 @@
    }
    if (param.custom_script) {
      param.custom_script = `declare @ErrorCode nvarchar(50),@retmsg nvarchar(4000),@UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@departmentcode nvarchar(50),@organization nvarchar(50),@login_city nvarchar(50) select @ErrorCode='',@retmsg ='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @departmentcode='${departmentcode}', @organization='${organization}', @login_city='${city}'
        ${param.custom_script}
      `
      regoptions.forEach(item => {
        param.custom_script = param.custom_script.replace(item.reg, item.value)
      })
@@ -615,17 +765,22 @@
            insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@
        `
      }
      param.custom_script = Utils.formatOptions(param.custom_script)
    }
    // 测试系统打印查询语句
    if ((options.sysType === 'local' && !window.GLOB.systemType) || window.debugger === true) {
      param.custom_script && console.info(`${LText ? '' : '/*不执行默认sql*/\n'}${param.custom_script}`)
      LText && console.info(LText)
    }
    param.custom_script = Utils.formatOptions(param.custom_script)
    param.LText = Utils.formatOptions(LText)
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss') + '.000'
    param.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
    param.secretkey = Utils.encrypt(param.LText, param.timestamp)
    param.DateCount = ''
    if (this.props.menuType === 'HS') { // 云端数据验证
      param.open_key = Utils.encrypt(param.secretkey, param.timestamp, true)
      param.open_key = Utils.encryptOpenKey(param.secretkey, param.timestamp)
    }
    return param
@@ -660,7 +815,9 @@
      loading: false
    })
    this.props.updateStatus('refresh', btn.execSuccess)
    if (btn.execSuccess !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execSuccess, btn)
    }
  }
  /**
@@ -697,37 +854,58 @@
      loading: false
    })
    this.props.updateStatus('refresh', btn.execError)
    if (btn.execError !== 'never') {
      MKEmitter.emit('refreshByButtonResult', btn.$menuId, btn.execError, btn)
    }
  }
  render() {
    const { btn, show } = this.props
    const { loading } = this.state
    return (
      <div className="mk-btn-wrap">
        {!show ? <Button
    if (show === 'actionList') {
      return (
        <Button
          className={'mk-btn mk-' + btn.class}
          icon={btn.icon}
          onClick={() => {this.actionTrigger()}}
          onClick={(e) => {e.stopPropagation(); this.actionTrigger()}}
          loading={loading}
        >{btn.label}</Button> : null}
        {show === 'icon' ? <Button
          className="export-icon"
          icon="download"
          onClick={() => {this.actionTrigger()}}
        >{btn.label}</Button>
      )
    } else { // icon、text、 all 卡片
      let label = ''
      let icon = ''
      if (show === 'button') {
        label = btn.label
        icon = btn.icon || ''
      } else if (show === 'link') {
        label = <span>{btn.label}{btn.icon ? <Icon style={{marginLeft: '8px'}} type={btn.icon}/> : ''}</span>
        icon = ''
      } else if (show === 'icon') {
        icon = btn.icon || 'download'
      // } else if (show === 'text') {
      } else {
        label = btn.label
      }
      return (
        <Button
          type="link"
          title={show === 'icon' ? btn.label : ''}
          loading={loading}
          title={btn.label}
        ></Button> : null}
      </div>
    )
          style={btn.style}
          icon={icon}
          onClick={(e) => {e.stopPropagation(); this.actionTrigger()}}
        >{label}</Button>
      )
    }
  }
}
const mapStateToProps = (state) => {
  return {
    menuType: state.editLevel,
    dataManager: state.dataManager
    menuType: state.editLevel
  }
}