From 58826d6f4eab9f8c9acf9fa8696f60039c645cfe Mon Sep 17 00:00:00 2001
From: king <18310653075@163.com>
Date: 星期二, 20 八月 2024 18:18:00 +0800
Subject: [PATCH] 2024-08-20

---
 src/menu/datasource/verifycard/index.jsx |  616 +++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 431 insertions(+), 185 deletions(-)

diff --git a/src/menu/datasource/verifycard/index.jsx b/src/menu/datasource/verifycard/index.jsx
index 8cc92cc..c7c6806 100644
--- a/src/menu/datasource/verifycard/index.jsx
+++ b/src/menu/datasource/verifycard/index.jsx
@@ -2,13 +2,12 @@
 import PropTypes from 'prop-types'
 import { fromJS } from 'immutable'
 import { Form, Tabs, Popconfirm, notification, Modal, Typography, Spin, message, Button, Input } from 'antd'
-import { StopOutlined, CheckCircleOutlined, EditOutlined, SwapOutlined, DeleteOutlined, CopyOutlined, BorderOutlined, SnippetsOutlined } from '@ant-design/icons'
+import { StopOutlined, CheckCircleOutlined, TableOutlined, EditOutlined, SwapOutlined, DeleteOutlined, CopyOutlined, BorderOutlined, SnippetsOutlined } from '@ant-design/icons'
 import moment from 'moment'
-import md5 from 'md5'
 
 import Api from '@/api'
 import Utils from '@/utils/utils.js'
-
+import { formatSearch, joinMainSearchkey } from '@/utils/utils-custom.js'
 import asyncComponent from '@/utils/asyncComponent'
 import ColForm from './columnform'
 import CustomScriptsForm from './customscript'
@@ -22,6 +21,7 @@
 const { TabPane } = Tabs
 const { Paragraph } = Typography
 const { Search } = Input
+const { confirm } = Modal
 
 const CodeMirror = asyncComponent(() => import('@/templates/zshare/codemirror'))
 const FieldsComponent = asyncComponent(() => import('@/templates/sharecomponent/fieldscomponent'))
@@ -29,7 +29,8 @@
 
 class VerifyCard extends Component {
   static propTpyes = {
-    config: PropTypes.object,        // 缁勪欢閰嶇疆淇℃伅
+    config: PropTypes.object,
+    updRecord: PropTypes.func
   }
 
   state = {
@@ -38,24 +39,27 @@
     subColumns: [],
     activeKey: 'setting',
     loading: false,
+    colLoading: false,
     searchKey: '',
-    initsql: '',          // sql楠岃瘉鏃跺彉閲忓0鏄庡強璧嬪��
     usefulfields: '',
-    defaultsql: '',       // 榛樿Sql
-    defaultSearch: '',
+    defaultsql: '',
     systemScripts: [],
     median: {},
     visible: false,
+    editLineId: '',
     pvisible: false,
     reload: false,
     script: null,
+    oriConfig: null,
     scriptValue: '',
+    cols: null,
     colColumns: [
       {
         title: '鍚嶇О',
         dataIndex: 'label',
         inputType: 'input',
         editable: true,
+        searchable: true,
         width: '28%'
       },
       {
@@ -65,6 +69,7 @@
         editable: true,
         unique: true,
         strict: true,
+        searchable: true,
         copy: true,
         rules: [{
           pattern: /^[\u4E00-\u9FA50-9a-zA-Z_]*$/ig,
@@ -85,6 +90,7 @@
           { value: 'Nvarchar(512)', text: 'Nvarchar(512)' },
           { value: 'Nvarchar(1024)', text: 'Nvarchar(1024)' },
           { value: 'Nvarchar(2048)', text: 'Nvarchar(2048)' },
+          { value: 'Nvarchar(4000)', text: 'Nvarchar(4000)' },
           { value: 'Nvarchar(max)', text: 'Nvarchar(max)' },
           { value: 'Int', text: 'Int' },
           { value: 'Decimal(18,0)', text: 'Decimal(18,0)' },
@@ -194,28 +200,46 @@
     let _setting = fromJS(config.setting).toJS()
     let scripts = config.scripts ? fromJS(config.scripts).toJS() : []
 
-    if (window.GLOB.funcs && window.GLOB.funcs.length > 0) {
-      window.GLOB.funcs.forEach(m => {
-        let reg = new RegExp(`\\/\\*\\$ex@${m.func_code}-begin\\*\\/[\\s\\S]+\\/\\*@ex\\$-end\\*\\/`, 'ig')
-        if (_setting.dataresource) {
-          _setting.dataresource = _setting.dataresource.replace(reg, `$ex@${m.func_code}@ex$`)
-        }
-        scripts && scripts.forEach(item => {
-          item.sql = item.sql.replace(reg, `$ex@${m.func_code}@ex$`)
-        })
-      })
-    }
+    // if (window.GLOB.funcs && window.GLOB.funcs.length > 0) {
+    //   window.GLOB.funcs.forEach(m => {
+    //     let reg = new RegExp(`\\/\\*\\$ex@${m.func_code}-begin\\*\\/[\\s\\S]+\\/\\*@ex\\$-end\\*\\/`, 'ig')
+    //     if (_setting.dataresource) {
+    //       _setting.dataresource = _setting.dataresource.replace(reg, `$ex@${m.func_code}@ex$`)
+    //     }
+    //     scripts && scripts.forEach(item => {
+    //       item.sql = item.sql.replace(reg, `$ex@${m.func_code}@ex$`)
+    //     })
+    //   })
+    // }
 
-    let _search = this.formatSearch(search)
-    _search = Utils.joinMainSearchkey(_search)
-
-    _search = _search.replace(/@\$@/ig, '')
-    _search = _search ? 'where ' + _search : ''
     let columns = config.columns ? fromJS(config.columns).toJS() : []
     let subColumns = config.subColumns ? fromJS(config.subColumns).toJS() : []
 
-    columns.reverse()
+    if (!config.fixedCol) {
+      columns.reverse()
+    }
     subColumns.reverse()
+    
+    columns.forEach(col => {
+      if (!col.datatype) return
+      if (/^nvarchar/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^nvarchar/, 'Nvarchar')
+      } else if (/^decimal/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^decimal/, 'Decimal')
+      } else if (/^int/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^int/, 'Int')
+      }
+    })
+    subColumns.forEach(col => {
+      if (!col.datatype) return
+      if (/^nvarchar/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^nvarchar/, 'Nvarchar')
+      } else if (/^decimal/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^decimal/, 'Decimal')
+      } else if (/^int/.test(col.datatype)) {
+        col.datatype = col.datatype.replace(/^int/, 'Int')
+      }
+    })
 
     this.setState({
       scripts,
@@ -223,10 +247,15 @@
       subColumns: subColumns,
       setting: _setting,
       median: _setting,
-      searches: search,
-      defaultSearch: _search,
+      searches: formatSearch(search),
       searchKey: '',
-      debugId: _setting.debugId || ''
+      debugId: _setting.debugId || '',
+      oriConfig: fromJS({
+        scripts,
+        columns: columns,
+        subColumns: subColumns,
+        setting: _setting
+      }).toJS()
     })
 
     this.getsysScript()
@@ -242,18 +271,18 @@
 
     let _scriptSql = `Select distinct func+Remark as funcname,longparam, s.Sort from聽 s_custom_script s inner join (select OpenID from sapp where ID=@Appkey@) p on s.openid = case when s.appkey='' then s.openid else p.OpenID end order by s.Sort`
 
-    _scriptSql = Utils.formatOptions(_scriptSql)
+    _scriptSql = Utils.formatOptions(_scriptSql, 'x')
 
     let _sParam = {
       func: 'sPC_Get_SelectedList',
       LText: _scriptSql,
       obj_name: 'data',
-      arr_field: 'funcname,longparam'
+      arr_field: 'funcname,longparam',
+      exec_type: 'x'
     }
     
     _sParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
-    _sParam.secretkey = Utils.encrypt(_sParam.LText, _sParam.timestamp)
-
+    _sParam.secretkey = Utils.encrypt('', _sParam.timestamp)
     _sParam.open_key = Utils.encryptOpenKey(_sParam.secretkey, _sParam.timestamp) // 浜戠鏁版嵁楠岃瘉
     
     Api.getCloudConfig(_sParam).then(res => {
@@ -371,6 +400,7 @@
     if (values.uuid) {
       scripts = scripts.map(item => {
         if (item.uuid === values.uuid) {
+          values.$index = item.$index || ''
           return values
         } else {
           return item
@@ -381,7 +411,7 @@
     }
 
     return new Promise((resolve, reject) => {
-      this.sqlverify(resolve, reject, false, scripts)
+      this.sqlverify(resolve, reject, 'script', scripts)
     })
   }
 
@@ -422,15 +452,8 @@
           search = [...search, ...mainSearch]
         }
 
-        let _search = this.formatSearch(search)
-        _search = Utils.joinMainSearchkey(_search)
-
-        _search = _search.replace(/@\$@/ig, '')
-        _search = _search ? 'where ' + _search : ''
-
         this.setState({
-          searches: search,
-          defaultSearch: _search,
+          searches: formatSearch(search),
           setting: res
         }, () => {
           this.sqlverify(() => { // 楠岃瘉鎴愬姛
@@ -445,7 +468,7 @@
               loading: false
             })
             this.getdefaultSql()
-          }, true)
+          }, 'change')
         })
       }, () => {
         this.setState({loading: false})
@@ -509,9 +532,11 @@
   }
 
   getdefaultSql = () => {
-    const { columns, setting, defaultSearch } = this.state
+    const { columns, setting, searches } = this.state
     let defaultsql = ''
     let arr_field = columns.map(col => col.field).join(',')
+
+    let _search = joinMainSearchkey(searches)
 
     if (setting.dataresource) {
       let _dataresource = setting.dataresource
@@ -520,64 +545,15 @@
         _dataresource = '(' + _dataresource + ') tb'
       }
 
-      defaultsql = `select top @pageSize@ ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by @orderBy@) as rows from ${_dataresource} ${defaultSearch}) tmptable where rows > (@pageSize@ * (@pageIndex@ - 1)) order by tmptable.rows`
+      defaultsql = `select top @pageSize@ ${arr_field} from (select ${arr_field} ,ROW_NUMBER() over(order by @orderBy@) as rows from ${_dataresource} ${_search}) tmptable where rows > (@pageSize@ * (@pageIndex@ - 1)) order by tmptable.rows`
     }
 
     this.setState({defaultsql})
   }
 
-  /**
-   * @description 鑾峰彇鍏ㄩ儴鎼滅储鏉′欢
-   * @param {Array} searches 鎼滅储鏉′欢鏁扮粍
-   */
-  formatSearch (searches) {
-    if (!searches) return []
-
-    let newsearches = []
-    searches.forEach(search => {
-      if (!search.field) return
-      
-      let item = {
-        key: search.field,
-        match: search.match,
-        type: search.type,
-        label: search.label,
-        value: search.initval,
-        required: search.required === 'true'
-      }
-      if (item.type === 'group') {
-        item.key = search.datefield
-        item.type = 'daterange'
-        item.match = 'between'
-        item.value = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')].join(',')
-
-        newsearches.push(item)
-        return
-      } else if (item.type === 'date') {
-        item.value = moment().format('YYYY-MM-DD')
-      } else if (item.type === 'datemonth') {
-        item.value = moment().format('YYYY-MM')
-      } else if (item.type === 'dateweek') {
-        item.value = moment().format('YYYY-MM-DD')
-      } else if (item.type === 'daterange') {
-        item.value = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')].join(',')
-      } else if (item.type === 'range') {
-
-      } else if (item.type === 'multiselect' || (item.type === 'checkcard' && search.multiple === 'true')) {
-        item.type = 'multi'
-        item.value = '@$@'
-      } else {
-        item.value = '@$@'
-      }
-      newsearches.push(item)
-    })
-
-    return newsearches
-  }
-
   submitDataSource = () => {
     const { config, mainSearch } = this.props
-    const { activeKey, setting, columns, subColumns, scripts } = this.state
+    const { activeKey, setting, columns, subColumns, scripts, cols, median, searches } = this.state
 
     if (config.subtype === 'dualdatacard') {
       let arr = columns.map(col => col.field.toLowerCase())
@@ -596,6 +572,42 @@
         })
         return Promise.reject()
       }
+    } else if (config.subtype === 'editable') {
+      let _arr = []
+      columns.forEach(col => {
+        let key = col.field.toLowerCase()
+        if (['jskey', 'data_type', 'bid'].includes(key)) {
+          _arr.push(col.field)
+        }
+      })
+
+      if (_arr.length > 0) {
+        notification.warning({
+          top: 92,
+          message: '瀛楁闆嗕腑涓嶅彲浣跨敤' + _arr.join('銆�') + '锛佹敞锛氭瀛楁涓烘彁浜ゆ椂鐨勭郴缁熷瓧娈点��',
+          duration: 5
+        })
+        return Promise.reject()
+      }
+    }
+
+    if (median.interType === 'system') {
+      let _loading = false
+      if (this.scriptsForm && this.scriptsForm.state.editItem) {
+        _loading = true
+      } else if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql') && !/^\s+$/.test(this.scriptsForm.props.form.getFieldValue('sql'))) {
+        _loading = true
+      }
+  
+      if (_loading) {
+        notification.warning({
+          top: 92,
+          message: '瀛樺湪鏈繚瀛樿剼鏈紝璇风偣鍑荤‘瀹氫繚瀛橈紝鎴栫偣鍑诲彇娑堟斁寮冧慨鏀癸紒',
+          duration: 5
+        })
+        this.setState({activeKey: 'scripts'})
+        return Promise.reject()
+      }
     }
 
     return new Promise((resolve, reject) => {
@@ -606,19 +618,13 @@
           if (res.useMSearch === 'true') { // 浣跨敤涓绘悳绱㈡潯浠�
             search = [...search, ...mainSearch]
           }
-
-          let _search = this.formatSearch(search)
-          _search = Utils.joinMainSearchkey(_search)
-
-          _search = _search.replace(/@\$@/ig, '')
-          _search = _search ? 'where ' + _search : ''
+          let _searches = formatSearch(search)
 
           this.setState({
-            searches: search,
-            defaultSearch: _search,
+            searches: _searches,
             setting: res
           }, () => {
-            this.sqlverify(() => { resolve({setting: res, columns, subColumns, scripts }) }, reject, false)
+            this.sqlverify(() => { resolve({setting: res, columns, subColumns, scripts, cols, searches: _searches }) }, reject, 'submit')
           })
         }, () => {
           reject()
@@ -633,7 +639,7 @@
           reject()
           return
         }
-        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts }) }, reject, false)
+        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts, cols, searches }) }, reject, 'submit')
       } else if (activeKey === 'subcolumns') {
         if (this.subdatasource && this.subdatasource.state.editingKey) {
           notification.warning({
@@ -644,40 +650,49 @@
           reject()
           return
         }
-        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts }) }, reject, false)
+        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts, cols, searches }) }, reject, 'submit')
       } else if (activeKey === 'scripts') {
-        let _loading = false
-        if (this.scriptsForm && this.scriptsForm.state.editItem) {
-          _loading = true
-        } else if (this.scriptsForm && this.scriptsForm.props.form.getFieldValue('sql') && !/^\s+$/.test(this.scriptsForm.props.form.getFieldValue('sql'))) {
-          _loading = true
-        }
-
-        if (_loading) {
-          notification.warning({
-            top: 92,
-            message: '瀛樺湪鏈繚瀛樿剼鏈紝璇风偣鍑荤‘瀹氫繚瀛橈紝鎴栫偣鍑诲彇娑堟斁寮冧慨鏀癸紒',
-            duration: 5
-          })
-          reject()
-          return
-        }
-
-        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts }) }, reject, false)
+        this.sqlverify(() => { resolve({setting, columns, subColumns, scripts, cols, searches }) }, reject, 'submit')
       }
     })
   }
 
-  sqlverify = (resolve, reject, change = false, testScripts) => {
+  closeDataSource = (callback) => {
+    const { setting, columns, subColumns, scripts, oriConfig } = this.state
+
+    let line = scripts.map(item => item.sql).join('')
+    line += columns.map(item => item.field + item.datatype).join('')
+    line += subColumns.map(item => item.field + item.datatype).join('')
+    line += setting.interType + (setting.dataresource || '') + (setting.order || '') + (setting.primaryKey || '')
+
+    let _line = oriConfig.scripts.map(item => item.sql).join('')
+    _line += oriConfig.columns.map(item => item.field + item.datatype).join('')
+    _line += oriConfig.subColumns.map(item => item.field + item.datatype).join('')
+    _line += oriConfig.setting.interType + (oriConfig.setting.dataresource || '') + (oriConfig.setting.order || '') + (oriConfig.setting.primaryKey || '')
+
+    if (line !== _line) {
+      confirm({
+        content: '鏁版嵁婧愬凡淇敼锛岀‘瀹氬彇娑堝悧锛�',
+        onOk() {
+          callback()
+        },
+        onCancel() {}
+      })
+    } else {
+      callback()
+    }
+  }
+
+  sqlverify = (resolve, reject, type, testScripts) => {
     const { config } = this.props
-    const { columns, setting, scripts, searches, defaultSearch, debugId } = this.state
+    const { columns, setting, scripts, searches, debugId, subColumns } = this.state
 
     let _scripts = scripts.filter(item => item.status !== 'false')
 
     if (testScripts) {
       _scripts = testScripts.filter(item => item.status !== 'false')
     }
-    if (!change && setting.interType === 'system' && setting.execute === 'false' && _scripts.length === 0) {
+    if (type !== 'change' && setting.interType === 'system' && setting.execute === 'false' && _scripts.length === 0) {
       notification.warning({
         top: 92,
         message: '涓嶆墽琛岄粯璁ql鏃讹紝璇锋坊鍔犺嚜瀹氫箟鑴氭湰锛�',
@@ -687,18 +702,39 @@
       return
     }
 
-    if (change && columns.length === 0) {
+    if (type === 'change' && columns.length === 0) {
       reject()
       return
     }
 
     if ((setting.interType === 'system' && setting.execute !== 'false') || _scripts.length > 0) {
-      let timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
-      let r = SettingUtils.getDebugSql(setting, _scripts, columns, searches, defaultSearch, config.type, '2023-04-20 15:29:37')
+      let _columns = columns
+      if (config.subtype === 'dualdatacard') {
+        _columns = [...columns, ...subColumns]
+      }
 
-      let _debugId = md5(r.sql)
+      let r = SettingUtils.getDebugSql(setting, _scripts, _columns, searches, config.subtype, config.hasExtend)
 
-      if (debugId === _debugId) {
+      if (r.custompage && setting.laypage === 'true' && _columns.findIndex(col => col.field === 'mk_total') === -1) {
+        if (config.subtype !== 'basetable') {
+          Modal.warning({
+            title: `鏁版嵁婧愭垨鑷畾涔夎剼鏈腑浣跨敤鑷畾涔夊垎椤垫帓搴忔椂锛岃鍦ㄥ瓧娈甸泦涓坊鍔� mk_total銆俙,
+            okText: '鐭ラ亾浜�',
+            onOk: () => {
+              reject()
+            }
+          })
+          return
+        } else {
+          notification.warning({
+            top: 92,
+            message: '鏁版嵁婧愭垨鑷畾涔夎剼鏈腑浣跨敤鑷畾涔夊垎椤垫帓搴忔椂锛岃鍦ㄦ樉绀哄垪涓坊鍔� mk_total銆�',
+            duration: 5
+          })
+        }
+      }
+
+      if (debugId === r.debugId) {
         resolve()
         return
       }
@@ -711,52 +747,82 @@
         })
       }
 
-      let param = {
-        func: 's_debug_sql',
-        exec_type: 'y',
-        LText: r.sql
-      }
-      param.LText = Utils.formatOptions(param.LText)
-      param.timestamp = timestamp
-      param.secretkey = Utils.encrypt('', timestamp)
+      Api.sDebug(r.sql).then(result => {
+        if (result.status || result.ErrCode === '-2') {
+          this.setState({debugId: r.debugId}, () => {
+            resolve()
+          })
+        } else {
+          if (/鍒楀悕\s*'[a-zA-Z0-9_-]+'\s*鏃犳晥/.test(result.message)) {
+            let tail = ''
+            let type = ''
+            if (setting.execute !== 'false' && setting.queryType !== 'statistics') {
+              searches.forEach(item => {
+                if (item.forbid) return
+                item.key.split(',').forEach(field => {
+                  if (new RegExp(`'${field}'`).test(result.message)) {
+                    tail = field
+                    type = '鎼滅储鏉′欢'
+                  }
+                })
+              })
+            }
 
-      let sumParam = null
-      if (r.sumSql) {
-        sumParam = {
-          func: 's_debug_sql',
-          exec_type: 'y',
-          LText: r.sumSql
-        }
-        sumParam.LText = Utils.formatOptions(sumParam.LText)
-        sumParam.timestamp = moment().format('YYYY-MM-DD HH:mm:ss')
-        sumParam.secretkey = Utils.encrypt('', sumParam.timestamp)
-      }
-      
-      Api.genericInterface(param).then(result => {
-        if (result.status) {
-          if (sumParam) {
-            Api.genericInterface(sumParam).then(res => {
-              if (res.status) {
-                this.setState({debugId: _debugId}, () => {
-                  resolve()
+            if (!tail && setting.order) {
+              let keys = setting.order.replace(/\s+(asc|desc)/ig, '').replace(/\s+/g, '')
+              keys.split(',').forEach(field => {
+                if (new RegExp(`'${field}'`).test(result.message)) {
+                  tail = field
+                  type = '鎺掑簭'
+                }
+              })
+            }
+
+            if (!tail) {
+              columns.forEach(item => {
+                if (new RegExp(`'${item.field}'`).test(result.message)) {
+                  tail = item.field
+                  if (config.subtype === 'basetable') {
+                    type = '鏄剧ず鍒�'
+                  } else {
+                    type = '瀛楁闆�'
+                  }
+                }
+              })
+              if (!tail && config.subtype === 'dualdatacard') {
+                subColumns.forEach(item => {
+                  if (new RegExp(`'${item.field}'`).test(result.message)) {
+                    tail = item.field
+                    type = '瀛愯〃瀛楁闆�'
+                  }
                 })
-              } else {
+              }
+            }
+
+            if (tail) {
+              result.message = result.message.replace(/ROLLBACK TRANSACTION 璇锋眰娌℃湁瀵瑰簲鐨� BEGIN TRANSACTION銆�/, '')
+              result.message = <>{result.message}<span style={{color: 'red'}}>娉細{type}涓瓨鍦ㄥ瓧娈祘tail}</span></>
+            }
+          }
+          if (type === 'submit') {
+            Modal.confirm({
+              title: result.message,
+              okText: '鐭ラ亾浜�',
+              cancelText: '寮哄埗淇濆瓨',
+              onOk: () => {
                 reject()
-                Modal.error({
-                  title: res.message
-                })
+              },
+              onCancel() {
+                resolve()
               }
             })
           } else {
-            this.setState({debugId: _debugId}, () => {
-              resolve()
+            reject()
+            Modal.error({
+              title: result.message,
+              okText: '鐭ラ亾浜�'
             })
           }
-        } else {
-          reject()
-          Modal.error({
-            title: result.message
-          })
         }
       })
     } else {
@@ -777,7 +843,9 @@
       return
     }
 
+    let editLineId = ''
     if (script) {
+      editLineId = script.uuid
       _scripts = _scripts.map(item => {
         if (script.uuid === item.uuid) {
           item.sql = scriptValue
@@ -792,12 +860,13 @@
         status: 'true'
       }
 
+      editLineId = _script.uuid
       _scripts.push(_script)
     }
 
-    this.setState({loading: true})
+    this.setState({loading: true, editLineId})
 
-    this.sqlverify(() => {this.setState({scripts: _scripts, script: null, scriptValue: '', loading: false})}, () => {this.setState({loading: false})}, false, _scripts)
+    this.sqlverify(() => {this.setState({scripts: _scripts, script: null, scriptValue: '', loading: false})}, () => {this.setState({loading: false})}, 'script', _scripts)
   }
 
   updatefields = (columns) => {
@@ -911,22 +980,98 @@
           this.setState({reload: false})
         })
       }
+
+      this.props.updRecord({...res.data.setting})
     })
   }
 
+  updateStatus = (res) => {
+    this.setState({median: {...res}})
+    this.props.updRecord({...res})
+  }
+
   copyColumns = () => {
-    const { columns } = this.state
+    const { config } = this.props
+    const { columns, subColumns, setting } = this.state
+
+    let _columns = columns
     let m = []
     let n = []
+    let s = []
 
-    columns.forEach(col => {
-      m.push(`${col.field} ${col.datatype}`)
-      n.push(col.field)
+    if (subColumns && subColumns.length) {
+      _columns = [...columns, ...subColumns]
+    }
+
+    _columns.forEach(col => {
+      m.unshift(`${col.field} ${col.datatype}`)
+      n.unshift(col.field)
+      if (/decimal|int/ig.test(col.datatype)) {
+        s.unshift(`${Math.round(Math.random() * 10)} as ${col.field}`)
+      } else if (/datetime/.test(col.datatype)) {
+        s.unshift(`'${moment().format('YYYY-MM-DD HH:mm:ss')}' as ${col.field}`)
+      } else if (/date/.test(col.datatype)) {
+        s.unshift(`'${moment().format('YYYY-MM-DD')}' as ${col.field}`)
+      } else {
+        s.unshift(`'${col.label}' as ${col.field}`)
+      }
     })
 
+    if (window.debugger) {
+      window.mkInfo('select ' + s.join(', '))
+    }
+
+    let extend = ''
+    if (config.hasExtend) {
+      extend = []
+      let mapCol = (cols) => {
+        cols.forEach(col => {
+          if (col.type === 'extend') {
+            let datatype = 'Nvarchar(50)'
+            _columns.forEach(c => {
+              if (c.field === col.field) {
+                datatype = c.datatype
+              }
+            })
+            for (let i = 1; i < col.quota; i++) {
+              extend.push(`${col.field}${i} ${datatype}`)
+            }
+          } else if (col.type === 'colspan' && col.subcols) {
+            mapCol(col.subcols)
+          }
+        })
+      }
+      mapCol(config.cols)
+      extend = `
+      /* 鎵╁睍鍒楀瓧娈� */
+      /* ${extend.join(',')} */
+      `
+    }
+
     let oInput = document.createElement('input')
-    oInput.value = `/*${m.join(',')}*/
-      ${n.join(',')}`
+    oInput.value = `create table #${setting.tableName || 'tb'}
+    (${m.join(',')},sort_id INT IDENTITY(1,1))
+    insert into #${setting.tableName || 'tb'}
+    (${n.join(',')})
+    select ${n.join(',')}
+    from ${setting.dataresource ? `(${setting.dataresource.replace(/\n/g, ' ')}) tb` : setting.tableName || 'tb'}
+    order by @orderBy@
+    
+    declare @mk_total int
+    set @mk_total = 0
+      
+    select @mk_total = count(1) from #${setting.tableName || 'tb'}
+      declare @pageIndex_top int 
+      set @pageIndex_top=(@pageIndex@-1)*@pageSize@ 
+      
+      if @mk_total > @pageIndex@*@pageSize@
+        delete #${setting.tableName || 'tb'} where sort_id > @pageIndex@*@pageSize@ 
+      
+      if @pageIndex_top > 0
+        delete #${setting.tableName || 'tb'} where sort_id <= @pageIndex_top
+
+    drop table #${setting.tableName || 'tb'}${extend}`
+
     document.body.appendChild(oInput)
     oInput.select()
     document.execCommand('Copy')
@@ -956,6 +1101,90 @@
     message.success('澶嶅埗鎴愬姛銆�')
   }
 
+  addProcess = () => {
+    const { config } = this.props
+    const { columns } = this.state
+
+    let fields = []
+    let cols = []
+    let _cols = columns.map(item => item.field.toLowerCase())
+
+    if (!_cols.includes('remark_w')) {
+      fields.push({ uuid: Utils.getuuid(), label: '澶囨敞', field: 'remark_w', datatype: 'Nvarchar(50)', fieldlength: 50, type: 'text' })
+      cols.push({ uuid: Utils.getuuid(), Width: 120, label: '澶囨敞', field: 'remark_w', type: 'text', Hide: 'false', IsSort: 'false', fieldlength: 50 })
+    }
+    if (!_cols.includes('statusname_w')) {
+      fields.push({ uuid: Utils.getuuid(), label: '鐘舵��', field: 'statusname_w', datatype: 'Nvarchar(50)', fieldlength: 50, type: 'text' })
+      cols.push({ uuid: Utils.getuuid(), Width: 120, label: '鐘舵��', field: 'statusname_w', type: 'text', Hide: 'false', IsSort: 'false', fieldlength: 50 })
+    }
+    if (!_cols.includes('works_flow_param')) {
+      fields.push({ uuid: Utils.getuuid(), label: '娴佺▼鍙傛暟', field: 'works_flow_param', datatype: 'Nvarchar(512)', fieldlength: 512, type: 'text' })
+      cols.push({ uuid: Utils.getuuid(), Width: 120, label: '娴佺▼鍙傛暟', field: 'works_flow_param', type: 'text', Hide: 'true', IsSort: 'false', fieldlength: 512 })
+    }
+
+    if (fields.length === 0) return
+
+    const that = this
+
+    if (config.subtype !== 'basetable') {
+      cols = null
+    }
+
+    confirm({
+      content: cols ? '鏄剧ず鍒椾腑鏄惁娣诲姞宸ヤ綔娴佸瓧娈碉紵' : '瀛楁闆嗕腑鏄惁娣诲姞宸ヤ綔娴佸瓧娈碉紵',
+      onOk() {
+        that.setState({
+          cols: cols,
+          columns: [...fields, ...columns]
+        })
+      },
+      onCancel() {}
+    })
+  }
+
+  updateColumns = (tableName) => {
+    const { config } = this.props
+    const { colLoading, columns } = this.state
+
+    if (colLoading || columns.length > 0) return
+
+    if (config.subtype === 'basetable') return
+
+    let param = {func: 'sPC_Get_FieldName', TBName: tableName}
+    if (window.GLOB.cloudServiceApi) { // 涓斿瓨鍦ㄤ簯绔湴鍧�
+      param.rduri = window.GLOB.cloudServiceApi
+      param.userid = sessionStorage.getItem('CloudUserID') || ''
+      param.LoginUID = sessionStorage.getItem('CloudLoginUID') || ''
+    }
+
+    this.setState({colLoading: true})
+
+    Api.getSystemCacheConfig(param).then(result => {
+      this.setState({colLoading: false})
+      if (!result.status) return
+
+      let fields = []
+      result.FDName.forEach(item => {
+        if (item.f_type !== 0) return
+
+        if (/nvarchar|int|decimal/ig.test(item.FieldType) || item.FieldType === 'date' || item.FieldType === 'datetime') {
+          fields.unshift({
+            uuid: Utils.getuuid(),
+            label: item.FieldDec,
+            field: item.FieldName,
+            datatype: item.FieldType.toLowerCase()
+          })
+        }
+      })
+
+      if (fields.length === 0) return
+
+      this.setState({columns: fields})
+    }, () => {
+      this.setState({colLoading: false})
+    })
+  }
+
   /**
    * @description 缁勪欢閿�姣侊紝娓呴櫎state鏇存柊
    */
@@ -967,7 +1196,7 @@
 
   render() {
     const { config } = this.props
-    const { columns, subColumns, median, setting, scripts, colColumns, scriptsColumns, activeKey, loading, searches, defaultsql, visible, pvisible, reload, script, scriptValue, searchKey } = this.state
+    const { columns, subColumns, median, setting, scripts, colColumns, scriptsColumns, activeKey, loading, searches, defaultsql, visible, pvisible, reload, script, scriptValue, searchKey, editLineId } = this.state
 
     return (
       <div className="model-data-source-wrap">
@@ -985,11 +1214,13 @@
               subColumns={subColumns}
               setting={setting}
               scripts={scripts}
-              updateStatus={(res) => this.setState({median: {...res}})}
+              updateStatus={this.updateStatus}
+              updateColumns={this.updateColumns}
+              addProcess={this.addProcess}
               wrappedComponentRef={(inst) => this.settingForm = inst}
             /> : null}
           </TabPane>
-          {config.subtype !== 'basetable' ? <TabPane tab={
+          {!['basetable', 'invoice', 'invTable'].includes(config.subtype) ? <TabPane tab={
             <span>
               瀛楁闆�
               {columns.length ? <span className="count-tip">{columns.length}</span> : null}
@@ -1002,7 +1233,15 @@
               updatefield={this.updatefields}
             />
             <EditTable actions={['edit', 'move', 'copy', 'del', 'clear']} searchKey={searchKey} type="datasourcefield" wrappedComponentRef={(inst) => this.datasource = inst} data={columns} columns={colColumns} onChange={(columns) => this.setState({columns})}/>
-          </TabPane> : null}
+          </TabPane> : <TabPane tab={
+            <span>
+              瀛楁闆�<TableOutlined style={{marginLeft: '5px', fontSize: '12px'}} />
+              {columns.length ? <span className="count-tip">{columns.length}</span> : null}
+            </span>
+          } key="columns">
+            <div className="base-table-columns"></div>
+            <EditTable actions={[]} searchKey={searchKey} type="datasourcefield" data={columns} columns={colColumns}/>
+          </TabPane>}
           {config.subtype === 'dualdatacard' ? <TabPane tab={
             <span>
               瀛愯〃瀛楁闆�
@@ -1021,8 +1260,8 @@
             <span>
               鑷畾涔夎剼鏈�
               {scripts.length ? <span className="count-tip">{scripts.length}</span> : null}
-              {config.type !== 'interface' && activeKey === 'setting' ? <CopyOutlined title="澶嶅埗鏁版嵁婧�" className="mk-copy-datasource" onClick={(e) => {e.stopPropagation();this.copyDatasource()}}/> : null}
-              {config.type !== 'interface' && activeKey === 'setting' ? <SnippetsOutlined title="瀵煎叆鏁版嵁婧�" className="mk-paste-datasource" onClick={(e) => {e.stopPropagation();this.setState({pvisible: true})}}/> : null}
+              {activeKey === 'setting' ? <CopyOutlined title="澶嶅埗鏁版嵁婧�" className="mk-copy-datasource" onClick={(e) => {e.stopPropagation();this.copyDatasource()}}/> : null}
+              {activeKey === 'setting' ? <SnippetsOutlined title="瀵煎叆鏁版嵁婧�" className="mk-paste-datasource" onClick={(e) => {e.stopPropagation();this.setState({pvisible: true})}}/> : null}
               {activeKey === 'columns' ? <CopyOutlined title="浠ラ�楀彿鎷兼帴褰㈠紡澶嶅埗瀛楁" className="mk-copy-fields" onClick={(e) => {e.stopPropagation();this.copyColumns()}}/> : null}
               {activeKey === 'subcolumns' ? <CopyOutlined title="浠ラ�楀彿鎷兼帴褰㈠紡澶嶅埗瀛楁" className="mk-copy-fields" onClick={(e) => {e.stopPropagation();this.copySubColumns()}}/> : null}
               {activeKey === 'subcolumns' || activeKey === 'columns' ? <span onClick={(e) => {e.stopPropagation()}}><Search className="mk-search-fields" defaultValue={searchKey} allowClear onSearch={(val, e) => {e.stopPropagation();this.setState({searchKey: val})}} /></span> : null}
@@ -1037,18 +1276,19 @@
                 })
                 return
               }
-              this.setState({visible: true, script: null, scriptValue: ''})
+              this.setState({visible: true, script: null, scriptValue: '', editLineId: ''})
             }}/> : null}
             <CustomScriptsForm
               type={config.type}
+              hasExtend={config.hasExtend}
               setting={setting}
               searches={searches}
               defaultsql={defaultsql}
-              initsql={this.state.initsql}
               customScripts={scripts}
               systemScripts={this.state.systemScripts}
               scriptsChange={this.scriptsChange}
               scriptSubmit={this.scriptSubmit}
+              addProcess={this.addProcess}
               wrappedComponentRef={(inst) => this.scriptsForm = inst}
             />
             <EditTable actions={['move']} data={scripts} columns={scriptsColumns} onChange={this.changeScripts}/>
@@ -1086,8 +1326,14 @@
                   </div>
                 )
               } else {
+                let sign = ''
+                if (script && script.uuid === item.uuid) {
+                  sign = 'active'
+                } else if (editLineId === item.uuid) {
+                  sign = 'edited'
+                }
                 return (
-                  <div className={'script-item ' + (script && script.uuid === item.uuid ? 'active' : '') } key={item.uuid}>
+                  <div className={'script-item ' + sign} key={item.uuid}>
                     <div style={{cursor: 'pointer'}} onClick={() => {
                       this.setState({script: item, scriptValue: item.sql})
                     }}>

--
Gitblit v1.8.0