king
2022-04-29 eec619b6e3339e9999a7a1c2c5454cef5d763b24
src/utils/utils.js
@@ -236,54 +236,82 @@
  }
  /**
   * @description 初始化搜索条件
   * @description 初始化搜索条件初始值
   * @param {Array}   searches     搜索条件
   * @return {String}  searches    格式化后结果
   */
  static initMainSearch (searches) {
    if (!searches || searches.length === 0) return []
  static initSearchVal (searches) {
    if (!searches) return []
    let newsearches = []
    searches.forEach(search => {
      let item = {
        key: search.field,
        match: search.match,
        type: search.type,
        label: search.label,
        value: search.initval,
        required: search.required === 'true'
      }
    let roleId = sessionStorage.getItem('role_id') || ''
      if (item.type === 'group') {
        let copy = JSON.parse(JSON.stringify(item))
        copy.key = search.datefield
    return searches.map(item => {
      item.hidden = item.Hide === 'true'
      item.required = !item.hidden && item.required === 'true'
      item.advanced = item.advanced === 'true'
      item.$forbid = item.query === 'false'
      item.precision = item.precision || 'day'
        item.value = search.initval && search.initval[0] ? search.initval[0] : ''
        item.match = '='
        item.forbid = true
        copy.type = 'daterange'
        copy.match = 'between'
        copy.value = ''
      if (item.type === 'date') { // 时间搜索
        let format = 'YYYY-MM-DD'
        if (item.precision === 'day') {
        if (search.initval && search.initval.length > 0) {
          let _type = search.initval[0]
          let _val = search.initval[1]
        } else if (item.precision === 'hour') {
          format = 'YYYY-MM-DD HH'
        } else if (item.precision === 'minute') {
          format = 'YYYY-MM-DD HH:mm'
        } else if (item.precision === 'second') {
          format = 'YYYY-MM-DD HH:mm:ss'
        }
        item.initval = item.initval ? moment().subtract(item.initval, 'days').format(format) : ''
      } else if (item.type === 'datemonth') {
        item.initval = item.initval ? moment().subtract(item.initval, 'month').format('YYYY-MM') : ''
      } else if (item.type === 'dateweek') {
        item.initval = item.initval ? moment().subtract(item.initval * 7, 'days').format('YYYY-MM-DD') : ''
      } else if (item.type === 'daterange') {
        let format = 'YYYY-MM-DD'
        if (item.precision === 'day') {
        } else if (item.precision === 'hour') {
          format = 'YYYY-MM-DD HH'
        } else if (item.precision === 'minute') {
          format = 'YYYY-MM-DD HH:mm'
        } else if (item.precision === 'second') {
          format = 'YYYY-MM-DD HH:mm:ss'
        }
        if (item.initval === 'week') {
          item.initval = [moment().startOf('week').format(format), moment().endOf('week').format(format)].join(',')
        } else if (item.initval === 'month') {
          item.initval = [moment().startOf('month').format(format), moment().endOf('month').format(format)].join(',')
        } else if (item.initval) {
          try {
            let _initval = JSON.parse(item.initval)
            let _vals = [moment().subtract(_initval[0], 'days').format(format), moment().subtract(_initval[1], 'days').format(format)]
            item.initval = _vals.join(',')
          } catch (e) {
            item.initval = ''
          }
        }
      } else if (item.type === 'group') {
        if (item.initval && item.initval[0]) {
          let _type = item.initval[0]
          let _val = item.initval[1]
          let _dateRange = ''
          if (_type === 'day') {
            copy.value = [moment().subtract(_val, 'days').format('YYYY-MM-DD'),
            _dateRange = [moment().subtract(_val, 'days').format('YYYY-MM-DD'),
              moment().subtract(_val, 'days').format('YYYY-MM-DD')]
          } else if (_type === 'week') {
            copy.value = [moment().subtract(_val * 7, 'days').startOf('week').format('YYYY-MM-DD'),
            _dateRange = [moment().subtract(_val * 7, 'days').startOf('week').format('YYYY-MM-DD'),
              moment().subtract(_val * 7, 'days').endOf('week').format('YYYY-MM-DD')]
          } else if (_type === 'month') {
            copy.value = [moment().subtract(_val, 'month').startOf('month').format('YYYY-MM-DD'),
            _dateRange = [moment().subtract(_val, 'month').startOf('month').format('YYYY-MM-DD'),
              moment().subtract(_val, 'month').endOf('month').format('YYYY-MM-DD')]
          } else if (_type === 'quarter') {
            let _differ = parseInt(moment().format('MM')) % 3
            let _pdiffer = 0
            let _ndiffer = 0
            // 差值计算
            switch(_differ) {
              case 0:
@@ -300,82 +328,118 @@
                break
              default:
            }
            copy.value = [moment().subtract(_pdiffer + _val * 3, 'month').startOf('month').format('YYYY-MM-DD'),
            _dateRange = [moment().subtract(_pdiffer + _val * 3, 'month').startOf('month').format('YYYY-MM-DD'),
              moment().subtract(_ndiffer + _val * 3, 'month').endOf('month').format('YYYY-MM-DD')]
          } else if (_type === 'year') {
            let _year = parseInt(moment().format('YYYY')) - _val
            copy.value = [_year + '-01-01', _year + '-12-31']
            _dateRange = [_year + '-01-01', _year + '-12-31']
          } else if (_type === 'customized') {
            try {
              _val = JSON.parse(_val)
            } catch {
            } catch (e) {
              _val = [0, 0]
            }
            copy.value = [moment().subtract(_val[0], 'days').format('YYYY-MM-DD'),
            _dateRange = [moment().subtract(_val[0], 'days').format('YYYY-MM-DD'),
              moment().subtract(_val[1], 'days').format('YYYY-MM-DD')]
          }
        }
        if (search.transfer === 'true') {
          newsearches.push(item)
          item.initval = _dateRange.join(',')
          item.initType = _type
        } else {
          item.initval = ''
          item.initType = ''
        }
        newsearches.push(copy)
        return
      } else if (item.type === 'date') {
        item.value = item.value ? moment().subtract(item.value, 'days').format('YYYY-MM-DD') : ''
      } else if (item.type === 'datemonth') {
        item.value = item.value ? moment().subtract(item.value, 'month').format('YYYY-MM') : ''
      } else if (item.type === 'dateweek') {
        item.value = item.value ? [moment().subtract(item.value * 7, 'days').startOf('week').format('YYYY-MM-DD'),
          moment().subtract(item.value * 7, 'days').endOf('week').format('YYYY-MM-DD')] : ''
      } else if (item.type === 'daterange') {
        let _val = item.value
        if (_val) {
          try {
            _val = JSON.parse(_val)
          } catch {
            _val = ''
          }
        }
        item.value = _val ? [moment().subtract(_val[0], 'days').format('YYYY-MM-DD'),
          moment().subtract(_val[1], 'days').format('YYYY-MM-DD')] : ''
      } else if (item.type === 'multiselect') {
        item.value = item.value ? item.value.split(',').filter(Boolean) : []
      }
      newsearches.push(item)
      item.oriInitval = item.initval
      if (item.blacklist && item.blacklist.length > 0 && !item.hidden) {
        if (item.blacklist.filter(v => roleId.indexOf(v) > -1).length > 0) {
          item.hidden = true
          item.required = false
        }
      }
      return item
    })
    return newsearches
  }
  /**
   * @description 初始化搜索条件
   * @param {Array}   searches     搜索条件
   * @return {String}  searches    格式化后结果
   */
  static initMainSearch (searches) {
    if (!searches) return []
    let values = []
    searches.forEach(cell => {
      let item = {
        key: cell.field,
        match: cell.match,
        type: cell.type,
        label: cell.label,
        value: cell.initval,
        required: cell.required,
        precision: cell.precision || 'day',
        forbid: cell.$forbid
      }
      if (cell.type === 'multiselect' || (cell.type === 'checkcard' && cell.multiple === 'true')) {
        item.type = 'multi'
      } else if (item.type === 'group') {
        item.key = cell.datefield
        item.type = 'daterange'
        item.match = 'between'
        values.push({
          type: 'group',
          key: cell.field,
          value: cell.initType,
          label: cell.label,
          match: '=',
          forbid: true,
          required: cell.required
        })
      }
      values.push(item)
    })
    return values
  }
  /**
   * @description 初始化自定义函数搜索条件
   * @param {Array}   searches     搜索条件
   */
  static formatCustomMainSearch (searches) {
    if (!searches || searches.length === 0) return {}
    if (!searches) return {}
    let newsearches = {}
    searches.forEach(item => {
      if (item.type === 'date') {
        let timetail = ''
        let _val = item.value
        let _val = item.value || ''
        if (item.match === '<' || item.match === '<=') {
          timetail = ' 00:00:00.000'
          if (_val) {
            _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
        if (_val) {
          if (item.precision === 'day') {
            if (item.match === '<' || item.match === '<=') {
              _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
            } else if (item.match === '>' || item.match === '>=') {
              _val = _val + ' 00:00:00.000'
            }
          } else if (item.precision === 'hour') {
            _val = _val + ':00:00.000'
          } else if (item.precision === 'minute') {
            _val = _val + ':00.000'
          } else if (item.precision === 'second') {
            _val = _val + '.000'
          }
        } else if (item.match === '>' || item.match === '>=') {
          timetail = ' 00:00:00.000'
        }
        if (newsearches[item.key]) {
          newsearches[item.key + '1'] = _val ? _val + timetail : ''
          newsearches[item.key + '1'] = _val
        } else {
          newsearches[item.key] = _val ? _val + timetail : ''
          newsearches[item.key] = _val
        }
      } else if (item.type === 'datemonth') {
        // 月-过滤条件,从月开始至结束
@@ -390,35 +454,44 @@
        newsearches[item.key] = _startval
        newsearches[item.key + '1'] = _endval
      } else if (item.type === 'dateweek') {
        let _startval = ''
        let _endval = ''
        if (item.value) {
          _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
          _startval = moment(item.value, 'YYYY-MM-DD' ).startOf('week').format('YYYY-MM-DD') + ' 00:00:00.000'
          _endval = moment(item.value, 'YYYY-MM-DD').endOf('week').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        }
        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : ''
        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : ''
        newsearches[item.key] = _startval
        newsearches[item.key + '1'] = _endval
      } else if (item.type === 'daterange') {
        let _startval = ''
        let _endval = ''
        if (item.value) {
          _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
          let val = item.value.split(',')
          if (item.precision === 'day') {
            _startval = val[0] + ' 00:00:00.000'
            _endval = moment(val[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
          } else if (item.precision === 'hour') {
            _startval = val[0] + ':00:00.000'
            _endval = val[1] + ':00:00.000'
          } else if (item.precision === 'minute') {
            _startval = val[0] + ':00.000'
            _endval = val[1] + ':00.000'
          } else if (item.precision === 'second') {
            _startval = val[0] + '.000'
            _endval = val[1] + '.000'
          }
        }
        newsearches[item.key] = item.value ? item.value[0] + ' 00:00:00.000' : ''
        newsearches[item.key + '1'] = item.value ? _endval + ' 00:00:00.000' : ''
        newsearches[item.key] = _startval
        newsearches[item.key + '1'] = _endval
      } else if (item.type === 'text' || item.type === 'select') {
        item.key.split(',').forEach(field => { // 综合搜索,所字段拼接
          newsearches[field] = item.value
        })
      } else if (item.type === 'multiselect') {
        newsearches[item.key] = item.value.join(',')
      } else {
        newsearches[item.key] = item.value
      }
    })
    Object.keys(newsearches).forEach(key => {
      if (!newsearches[key]) {
        delete newsearches[key]
      }
    })
    
@@ -433,55 +506,87 @@
  static joinMainSearchkey (searches) {
    if (!searches || searches.length === 0) return ''
    let searchText = ''
    let searchText = []
    searches.forEach(item => {
      if (item.forbid || !item.value || (item.type === 'multiselect' && item.value.length === 0)) return
      if (item.forbid || !item.value) return
      
      searchText += (searchText !== '' ? ' AND ' : '')
      if (item.type === 'text' || item.type === 'select') { // 综合搜索,文本或下拉,所有字段拼接
        let str = item.match === '=' ? '' : '%'
        let str = item.match === 'like' || item.match === 'not like' ? '%' : ''
        let fields = item.key.split(',').map(field => {
          return field + ' ' + item.match + ' \'' + str + item.value + str + '\''
        })
        searchText += '(' + fields.join(' OR ') + ')'
      } else if (item.type === 'multiselect') {
        searchText.push('(' + fields.join(' OR ') + ')')
      } else if (item.type === 'checkcard') {
        let str = item.match === 'like' || item.match === 'not like' ? '%' : ''
        searchText += `'${item.value}' ` + item.match + ' \'%\'+' + item.key + '+\'%\''
        searchText.push('(' + item.key + ' ' + item.match + ' \'' + str + item.value + str + '\')')
      } else if (item.type === 'multi') {
        searchText.push(`('${item.value}' ${item.match} '%'+${item.key}+'%')`)
      } else if (item.type === 'date') {
        let _val = item.value
        let timetail = ' 00:00:00.000'
        let timetail = ''
        let _match = item.match
        if (item.match === '<' || item.match === '<=') { // 时间为<=时,匹配后一天的0点,匹配方式为<
          _match = '<'
          _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
        } else if (item.match === '=') {
          if (item.precision === 'day') {
            _val = moment(_val, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD')
          }
        }
        if (item.match === '=') {
          timetail = ''
        } else if (item.precision === 'day') {
          timetail = ' 00:00:00.000'
        } else if (item.precision === 'hour') {
          timetail = ':00:00.000'
        } else if (item.precision === 'minute') {
          timetail = ':00.000'
        } else if (item.precision === 'second') {
          timetail = '.000'
        }
        searchText += '(' + item.key + ' ' + _match + ' \'' + _val + timetail + '\')'
        searchText.push('(' + item.key + ' ' + _match + ' \'' + _val + timetail + '\')')
      } else if (item.type === 'datemonth') { // 月-过滤条件,从月开始至结束,结束时间为月末加一天的0点,方式为<
        let _startval = moment(item.value, 'YYYY-MM').startOf('month').format('YYYY-MM-DD') + ' 00:00:00.000'
        let _endval = moment(item.value, 'YYYY-MM').endOf('month').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
        searchText.push('(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')')
      } else if (item.type === 'dateweek') { // 周-过滤条件
        let _startval = item.value[0] + ' 00:00:00.000'
        let _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        let _startval = moment(item.value, 'YYYY-MM-DD' ).startOf('week').format('YYYY-MM-DD') + ' 00:00:00.000'
        let _endval = moment(item.value, 'YYYY-MM-DD').endOf('week').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
        searchText.push('(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')')
      } else if (item.type === 'daterange') {
        let _startval = item.value[0] + ' 00:00:00.000'
        let _endval = moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        let val = item.value.split(',')
        let _startval = ''
        let _endval = ''
        searchText += '(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')'
        if (item.precision === 'day') {
          _startval = val[0] + ' 00:00:00.000'
          _endval = moment(val[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
        } else if (item.precision === 'hour') {
          _startval = val[0] + ':00:00.000'
          _endval = val[1] + ':00:00.000'
        } else if (item.precision === 'minute') {
          _startval = val[0] + ':00.000'
          _endval = val[1] + ':00.000'
        } else if (item.precision === 'second') {
          _startval = val[0] + '.000'
          _endval = val[1] + '.000'
        }
        searchText.push('(' + item.key + ' >= \'' + _startval + '\' AND ' + item.key + ' < \'' + _endval + '\')')
      } else if (item.type === 'range') {
        let val = item.value.split(',')
        searchText.push('(' + item.key + ' >= \'' + val[0] + '\' AND ' + item.key + ' < \'' + val[1] + '\')')
      } else {
        searchText += '(' + item.key + ' ' + item.match + ' \'' + item.value + '\')'
        searchText.push('(' + item.key + ' ' + item.match + ' \'' + item.value + '\')')
      }
    })
    return searchText
    return searchText.join(' AND ')
  }
  /**
@@ -509,10 +614,24 @@
      fieldmap.set(item.key, true)
      if (item.type === 'date') {
        if (['>=', '>'].includes(item.match)) {
          item.value = item.value ? item.value + ' 00:00:00.000' : '1970-01-01 00:00:00.000'
        } else if (['<=', '<'].includes(item.match)) {
          item.value = item.value ? moment(item.value, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2050-01-01 00:00:00.000'
        if (!item.value) {
          if (['>=', '>'].includes(item.match)) {
            item.value = '1970-01-01 00:00:00.000'
          } else if (['<=', '<'].includes(item.match)) {
            item.value = '2050-01-01 00:00:00.000'
          }
        } else if (search.precision === 'day') {
          if (['>=', '>'].includes(item.match)) {
            item.value = item.value + ' 00:00:00.000'
          } else if (['<=', '<'].includes(item.match)) {
            item.value = moment(item.value, 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
          }
        } else if (search.precision === 'hour') {
          item.value = item.value + ':00:00.000'
        } else if (search.precision === 'minute') {
          item.value = item.value + ':00.000'
        } else if (search.precision === 'second') {
          item.value = item.value + '.000'
        }
        options.push(item)
@@ -529,8 +648,8 @@
        options.push(item)
        options.push(copy)
      } else if (item.type === 'dateweek') {
        let _startval = item.value && item.value[0] ? moment(item.value[0], 'YYYY-MM-DD').format('YYYY-MM-DD') + ' 00:00:00.000' : '1970-01-01 00:00:00.000'
        let _endval = item.value && item.value[1] ? moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2050-01-01 00:00:00.000'
        let _startval = item.value ? moment(item.value, 'YYYY-MM-DD').startOf('week').format('YYYY-MM-DD') + ' 00:00:00.000' : '1970-01-01 00:00:00.000'
        let _endval = item.value ? moment(item.value, 'YYYY-MM-DD').endOf('week').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2050-01-01 00:00:00.000'
        let copy = JSON.parse(JSON.stringify(item))
        copy.key = copy.key + '1'
@@ -541,8 +660,26 @@
        options.push(item)
        options.push(copy)
      } else if (item.type === 'daterange') {
        let _startval = item.value && item.value[0] ? item.value[0] + ' 00:00:00.000' : '1970-01-01 00:00:00.000'
        let _endval = item.value && item.value[1] ? moment(item.value[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000' : '2050-01-01 00:00:00.000'
        let _startval = '1970-01-01 00:00:00.000'
        let _endval = '2050-01-01 00:00:00.000'
        if (item.value) {
          let val = item.value.split(',')
          if (search.precision === 'day') {
            _startval = val[0] + ' 00:00:00.000'
            _endval = moment(val[1], 'YYYY-MM-DD').add(1, 'days').format('YYYY-MM-DD') + ' 00:00:00.000'
          } else if (search.precision === 'hour') {
            _startval = val[0] + ':00:00.000'
            _endval = val[1] + ':00:00.000'
          } else if (search.precision === 'minute') {
            _startval = val[0] + ':00.000'
            _endval = val[1] + ':00.000'
          } else if (search.precision === 'second') {
            _startval = val[0] + '.000'
            _endval = val[1] + '.000'
          }
        }
        let copy = JSON.parse(JSON.stringify(item))
        copy.key = copy.key + '1'
@@ -552,10 +689,6 @@
        options.push(item)
        options.push(copy)
      } else if (item.type === 'multiselect') {
        item.value = item.value ? item.value.join(',') : item.value
        options.push(item)
      } else if (item.type === 'text' || item.type === 'select') {
        item.key.split(',').forEach(field => { // 综合搜索,所字段拼接
          let cell = JSON.parse(JSON.stringify(item))
@@ -595,12 +728,18 @@
      if (search.type === 'group') {
        options.push({
          key: search.field,
          value: '0'
        })
        options.push({
          key: search.datefield,
          value: '0'
        })
        if (search.transfer === 'true') {
          options.push(item)
        }
        options.push({
          key: search.datefield + '1',
          value: '0'
        })
        options.push(item)
      } else if (['datemonth', 'dateweek', 'daterange'].includes(search.type)) {
        options.push(item)
        options.push({
@@ -620,33 +759,6 @@
    })
    return options
  }
  /**
   * @description 拼接搜索条件datamanage
   * @param {Array}   searches     搜索条件
   * @return {String}  searchText  拼接结果
   */
  static jointsearchkey (searches) {
    if (!searches || searches.length === 0) return ''
    let searchText = ''
    searches.forEach(item => {
      if (!item.value) return
      searchText += (searchText !== '' ? ' AND ' : '')
      if (item.type === 'text') {
        let options = item.key.split(',').map(op => {
          // equal时不添加%
          let str = item.op === 'equal' ? '' : '%'
          return op + ' ' + item.op + ' \'' + str + item.value + str + '\''
        })
        searchText += '(' + options.join(' OR ') + ')'
      } else if (item.type === 'date') {
        searchText += '(' + item.key + ' ' + item.op + ' \'' + item.value + '\')'
      } else {
        searchText += '(' + item.key + ' ' + item.op + ' \'' + item.value + '\')'
      }
    })
    return searchText
  }
  /**
@@ -692,13 +804,22 @@
  static getSelectQueryOptions (item) {
    let arrfield = [item.valueField, item.valueText]
    if (item.type === 'link') {
      arrfield.push(item.linkField)
    } else if ((item.type === 'select' || item.type === 'radio') && item.linkSubField && item.linkSubField.length > 0) {
      arrfield.push(...item.linkSubField)
    } else if (item.type === 'checkcard') {
    if (item.type === 'checkcard') {
      arrfield = item.fields.map(f => f.field)
      arrfield.push(item.valueField)
      arrfield.push(item.cardValField)
      if (item.urlField) {
        arrfield.push(item.urlField)
      }
    }
    if (item.linkField) {
      arrfield.push(item.linkField)
    }
    if (['select', 'radio', 'link', 'checkcard'].includes(item.type) && item.linkSubField && item.linkSubField.length > 0) {
      arrfield.push(...item.linkSubField)
    }
    if (item.disableField) {
      arrfield.push(item.disableField)
    }
    arrfield = Array.from(new Set(arrfield))
@@ -713,9 +834,27 @@
    arrfield = arrfield.join(',')
    if (item.orderBy) {
      sql = `select ${item.type === 'checkcard' ? 'top 20' : ''} ${arrfield} from (select distinct ${arrfield},${item.orderBy} as orderfield from ${_datasource} ) a order by orderfield ${item.orderType}`
      // sql = `select ${item.type === 'checkcard' ? 'top 20' : ''} ${arrfield} from (select distinct ${arrfield},${item.orderBy} as orderfield from ${_datasource} ) a order by orderfield ${item.orderType}`
      sql = `select distinct ${arrfield},${item.orderBy} as orderfield from ${_datasource} order by orderfield ${item.orderType}`
    } else {
      sql = `select ${item.type === 'checkcard' ? 'top 20' : ''} ${arrfield} from (select distinct ${arrfield} from ${_datasource}) a`
      // sql = `select ${item.type === 'checkcard' ? 'top 20' : ''} ${arrfield} from (select distinct ${arrfield} from ${_datasource}) a`
      sql = `select distinct ${arrfield} from ${_datasource}`
    }
    if (sessionStorage.getItem('dataM') === 'true') { // 数据权限
      sql = sql.replace(/\$@/ig, '/*')
      sql = sql.replace(/@\$/ig, '*/')
    } else {
      sql = sql.replace(/@\$|\$@/ig, '')
    }
    // 外联数据库替换
    if (window.GLOB.externalDatabase !== null) {
      sql = sql.replace(/@db@/ig, window.GLOB.externalDatabase)
    }
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      console.info(sql)
    }
    return {
@@ -723,947 +862,1833 @@
      field: arrfield
    }
  }
}
  /**
   * @description 获取excel导入参数
   * @return {String} btn   按钮
   * @return {String} data  excel数据
   */
  static getExcelInSql (item, data, dict, BID) {
    let btn = item.verify
    let keys = ['delete', 'drop', 'insert', 'truncate', 'update']
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
/**
 * @description 获取excel导入参数
 * @return {Object} item   按钮信息
 * @return {Array}  data   excel数据
 * @return {Object} dict   字典项
 * @return {String} BID    上级Id
 */
export function getExcelInSql (item, data, dict, BID) {
  let btn = item.verify
  let keys = ['delete', 'drop', 'insert', 'truncate', 'update']
  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') || ''
  let _sheet = item.sheet
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
  if (sessionStorage.getItem('isEditState') === 'true') {
    userName = sessionStorage.getItem('CloudUserName') || ''
    fullName = sessionStorage.getItem('CloudFullName') || ''
  }
  if (window.GLOB.externalDatabase !== null) {
    _sheet = _sheet.replace(/@db@/ig, window.GLOB.externalDatabase)
  }
  let database = _sheet.match(/(.*)\.(.*)\./ig)
  let sheet = _sheet.replace(/(.*)\.(.*)\./ig, '')
  database = database ? (database[0] || '') : ''
  let getuuid = () => {
    let uuid = []
    let timestamp = new Date().getTime()
    let _options = '0123456789abcdefghigklmnopqrstuv'
    for (let i = 0; i < 19; i++) {
      uuid.push(_options.substr(Math.floor(Math.random() * 0x20), 1))
    }
    uuid = timestamp + uuid.join('')
    return uuid
  }
    let database = item.sheet.match(/(.*)\.(.*)\./ig) || ''
    let sheet = item.sheet.replace(/(.*)\.(.*)\./ig, '')
  let errors = []
  let _topline = btn.range || 0
  let upId = getuuid()
    let errors = []
    let _topline = btn.range || 0
    let upId = this.getuuid()
  let _initCustomScript = '' // 初始化脚本
  let _prevCustomScript = '' // 默认sql前执行脚本
  let _backCustomScript = '' // 默认sql后执行脚本
    let _initCustomScript = '' // 初始化脚本
    let _prevCustomScript = '' // 默认sql前执行脚本
    let _backCustomScript = '' // 默认sql后执行脚本
  if (btn.scripts) {
    btn.scripts.forEach(script => {
      if (script.status === 'false') return
    if (btn.scripts) {
      btn.scripts.forEach(script => {
        if (script.status === 'false') return
      if (script.position === 'init') {
        _initCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      } else if (script.position === 'front') {
        _prevCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      } else {
        _backCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      }
    })
  }
        if (script.position === 'init') {
          _initCustomScript += `
        /* 自定义脚本 */
        ${script.sql}
        `
        } else if (script.position === 'front') {
          _prevCustomScript += `
        /* 自定义脚本 */
        ${script.sql}
        `
        } else {
          _backCustomScript += `
        /* 自定义脚本 */
        ${script.sql}
        `
  // 控制台打印数据
  let conLtext = []
  let cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  for (let i = 0; i < 26; i++) {
    cols.push('A' + cols[i])
  }
  let _Ltext = data.map((item, lindex) => {
    let vals = []
    let convals = []
    btn.columns.forEach((col, cindex) => {
      if (col.import === 'false') return
      let val = item[col.Column] !== undefined ? item[col.Column] : ''
      let _colindex = cols[cindex] || (cindex + 1)
      let _position = (_topline + lindex + 1) + dict['main.excel.line'] + ' ' + _colindex + dict['main.excel.column']  + ' '
      if (/^Nvarchar/ig.test(col.type)) {
        if (typeof(val) === 'number') {
          val = val.toString()
        }
      })
    }
    // 控制台打印数据
    let conLtext = []
    let _Ltext = data.map((item, lindex) => {
      let vals = []
      let convals = []
      btn.columns.forEach((col, cindex) => {
        if (col.import === 'false') return
        val = val.replace(/(^\s*$)|\t*|\v*|'*/ig, '')
        let val = item[col.Column] !== undefined ? item[col.Column] : ''
        let _position = (_topline + lindex + 1) + dict['main.excel.line'] + ' ' + (cindex + 1) + dict['main.excel.column']  + ' '
        if (!val && col.required === 'true') {            // 必填校验
          errors.push(_position + dict['main.excel.content.emptyerror'])
        } else if (col.limit && val.length > col.limit) { // 长度校验
          errors.push(_position + dict['main.excel.content.maxlimit'])
        } else {                                          // 关键字校验
          keys.forEach(key => {
            let _patten = new RegExp('(^' + key + '\\s+)|(\\s+' + key + '\\s+)', 'ig')
            if (_patten.test(val)) {
              errors.push(_position + dict['main.excel.includekey'] + key)
            }
          })
        }
      } else if (/^int/ig.test(col.type)) {
        if (!val && val !== 0) {
          errors.push(_position + dict['main.excel.content.emptyerror'])
        } else {
          let _val = val + ''
        if (/^Nvarchar/ig.test(col.type)) {
          if (typeof(val) === 'number') {
            val = val.toString()
          if (!/^(([^0][0-9]+|0)$)|^(([1-9]+)$)/.test(_val)) {               // 检验是否为整数
            errors.push(_position + dict['main.excel.content.interror'])
          } else if ((col.min || col.min === 0) && val < col.min) {          // 最小值检验
            errors.push(_position + dict['main.excel.content.limitmin'])
          } else if ((col.max || col.max === 0) && val > col.max) {          // 最大值检验
            errors.push(_position + dict['main.excel.content.limitmax'])
          }
        }
      } else if (/^Decimal/ig.test(col.type)) {
        if (!val && val !== 0) {
          errors.push(_position + dict['main.excel.content.emptyerror'])
        } else {
          let _val = val + ''
          let _vals = _val.split('.')
          if (!/^(([^0][0-9]+|0)\.([0-9]+)$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]+)$)|^(([1-9]+)$)/.test(_val)) {                           // 检验是否为浮点数
            errors.push(_position + dict['main.excel.content.floaterror'])
          } else if (_vals[0].length > 18) {                          // 检验整数位
            errors.push(_position + dict['main.excel.content.floatIntover'])
          } else if (_vals[1] && _vals[1].length > col.limit) {       // 最小值检验
            errors.push(_position + dict['main.excel.content.floatPointover'])
          } else if ((col.min || col.min === 0) && val < col.min) {   // 最小值检验
            errors.push(_position + dict['main.excel.content.limitmin'])
          } else if ((col.max || col.max === 0) && val > col.max) {   // 最大值检验
            errors.push(_position + dict['main.excel.content.limitmax'])
          }
        }
      } else if (col.type === 'date') {
        if (typeof(val) === 'number') {
          if (val > 2958465 || val <= 0) {                 // 时间过大或小于等于0
            errors.push(_position + dict['main.excel.content.date.over'])
          } else {                                         // 时间格式化
            if (val < 60) {                                // 1900-2-29,excel中存在,实际不存在
              val++
            }
            val = moment('19000101', 'YYYYMMDD').add(Math.floor(val - 2), 'days').format('YYYY-MM-DD')
          }
        } else if (typeof(val) === 'string') {
          val = val.replace(/(^\s*$)|\t*|\v*/ig, '')
          if (!val && col.required === 'true') {            // 必填校验
          if (!val && col.required === 'true') {           // 时间必填校验
            errors.push(_position + dict['main.excel.content.emptyerror'])
          } else if (col.limit && val.length > col.limit) { // 长度校验
            errors.push(_position + dict['main.excel.content.maxlimit'])
          } else {                                          // 关键字校验
            keys.forEach(key => {
              let _patten = new RegExp('(^' + key + '\\s+)|(\\s+' + key + '\\s+)', 'ig')
              if (_patten.test(val)) {
                errors.push(_position + dict['main.excel.includekey'] + key)
              }
            })
          }
        } else if (/^int/ig.test(col.type)) {
          if (!val && val !== 0) {
            errors.push(_position + dict['main.excel.content.emptyerror'])
          } else {
            let _val = val + ''
            if (!/^(([^0][0-9]+|0)$)|^(([1-9]+)$)/.test(_val)) {               // 检验是否为整数
              errors.push(_position + dict['main.excel.content.interror'])
            } else if ((col.min || col.min === 0) && val < col.min) {          // 最小值检验
              errors.push(_position + dict['main.excel.content.limitmin'])
            } else if ((col.max || col.max === 0) && val > col.max) {          // 最大值检验
              errors.push(_position + dict['main.excel.content.limitmax'])
            }
          }
        } else if (/^Decimal/ig.test(col.type)) {
          if (!val && val !== 0) {
            errors.push(_position + dict['main.excel.content.emptyerror'])
          } else {
            let _val = val + ''
            let _vals = _val.split('.')
            if (!/^(([^0][0-9]+|0)\.([0-9]+)$)|^(([^0][0-9]+|0)$)|^(([1-9]+)\.([0-9]+)$)|^(([1-9]+)$)/.test(_val)) {                           // 检验是否为浮点数
              errors.push(_position + dict['main.excel.content.floaterror'])
            } else if (_vals[0].length > 18) {                          // 检验整数位
              errors.push(_position + dict['main.excel.content.floatIntover'])
            } else if (_vals[1] && _vals[1].length > col.limit) {       // 最小值检验
              errors.push(_position + dict['main.excel.content.floatPointover'])
            } else if ((col.min || col.min === 0) && val < col.min) {   // 最小值检验
              errors.push(_position + dict['main.excel.content.limitmin'])
            } else if ((col.max || col.max === 0) && val > col.max) {   // 最大值检验
              errors.push(_position + dict['main.excel.content.limitmax'])
            }
          }
        } else if (col.type === 'date') {
          if (typeof(val) === 'number') {
            if (val > 2958465 || val <= 0) {                 // 时间过大或小于等于0
              errors.push(_position + dict['main.excel.content.date.over'])
            } else {                                         // 时间格式化
              if (val < 60) {                                // 1900-2-29,excel中存在,实际不存在
                val++
              }
              val = moment('19000101', 'YYYYMMDD').add(Math.floor(val - 2), 'days').format('YYYY-MM-DD')
            }
          } else if (typeof(val) === 'string') {
            val = val.replace(/(^\s*$)|\t*|\v*/ig, '')
            if (!val && col.required === 'true') {           // 时间必填校验
              errors.push(_position + dict['main.excel.content.emptyerror'])
            } else if (val && !/^[1-9][0-9]{3}/.test(val)) { // 时间正则校验
              errors.push(_position + dict['main.excel.content.date.formatError'])
            }
          } else {                                           // 时间格式错误
          } else if (val && !/^[1-9][0-9]{3}/.test(val)) { // 时间正则校验
            errors.push(_position + dict['main.excel.content.date.formatError'])
          }
        } else {                                           // 时间格式错误
          errors.push(_position + dict['main.excel.content.date.formatError'])
        }
      }
      vals.push(`'${val}'`)
      if (lindex < 40) {
        convals.push(`'${val}' as ${col.Column}`)
      }
    })
    let _lineIndex = '0000' + (lindex + 1) + '0'
    _lineIndex = _lineIndex.substring(_lineIndex.length - 6)
    vals.push(`'${upId + _lineIndex}'`)
    vals.push(`'${BID}'`)
    if (lindex < 40) {
      convals.push(`'${upId + _lineIndex}' as jskey`)
      convals.push(`'${BID}' as BID`)
      conLtext.push(`Select ${convals.join(',')}`)
    }
    return `Select ${vals.join(',')}`
  })
  let result = []
  for(let i = 0; i < _Ltext.length; i += 20) {
    result.push(_Ltext.slice(i, i + 20))
  }
  let _sql = ''
  let _sqlInsert = ''
  let _sqlBottom = ''
  if (item.intertype === 'system') {
    let _uniquesql = ''
    if (btn.uniques && btn.uniques.length > 0) {
      btn.uniques.forEach(unique => {
        if (unique.status === 'false') return
        let _fields = unique.field.split(',')
        let _fields_ = _fields.map(_field => `a.${_field}=b.${_field}`)
        let _afields = _fields.map(_field => `a.${_field}`)
        _fields_ = _fields_.join(' and ')
        if (unique.verifyType !== 'physical') {
          _fields_ += ' and b.deleted=0'
        }
        vals.push(`'${val}'`)
        _uniquesql += `
      /* 重复性验证 */
      Set @tbid=''
      Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${sheet} ) a group by ${unique.field} having sum(n)>1
      If @tbid!=''
      Begin
        select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 重复'
        goto aaa
      end
      Set @tbid=''
      Select top 1 @tbid=${_afields.join('+\' \'+')} from  @${sheet} a Inner join ${sheet} b on ${_fields_}
      If @tbid!=''
      Begin
        select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 与已有数据重复'
        goto aaa
      end
      `
      })
    }
        if (lindex < 40) {
          convals.push(`'${val}' as ${col.Column}`)
    let declarefields = []
    let fields = []
    btn.columns.forEach(col => {
      if (col.import === 'false') return
      if (col.type === 'date') {
        declarefields.push(`${col.Column} Nvarchar(50)`)
      } else {
        declarefields.push(`${col.Column} ${col.type}`)
      }
      fields.push(col.Column)
    })
    fields = fields.join(',')
    let _insert = ''
    if (btn.default !== 'false') {
      _insert = `
      /* 默认sql */
      Insert into ${database}${sheet} (${fields},createuserid,createuser,createstaff,bid)
      Select ${fields},@userid@,@username,@fullname,@BID@ From @${sheet}
      `
    }
    _sql = `
      /* 系统生成 */
      declare @${sheet} table (${declarefields.join(',')},jskey nvarchar(50),BID nvarchar(50) )
      Declare @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
      Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
      ${_initCustomScript}
      `
    _sqlInsert = `Insert into @${sheet} (${fields},jskey,BID)`
    _sqlBottom = `
      /* 默认sql */
      delete tmp_excel_in where upid=@upid@
      delete tmp_excel_in where datediff(day,createdate,getdate())>15
      ${_uniquesql}
      ${_prevCustomScript}
      ${_insert}
      ${_backCustomScript}
      Delete @${sheet}
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      let fsql = `
      ${_sql}
      ${_sqlInsert}
      /* excel数据(前40条) */
      ${conLtext.join(' Union all ')}
      ${_sqlBottom}
      `
      fsql = fsql.replace(/\n\s{8}/ig, '\n')
      console.info(fsql)
    }
  } else { // s_sDataDictb_excelIn 云端密钥验证参数
    _sql = `
      /* 系统生成 */
      declare @${sheet} table (jskey nvarchar(50))
      Declare @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
      Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
      `
  }
  return {
    sql: _sql,
    lines: result.map((list, index) => {
      return {
        Ltext: window.btoa(window.encodeURIComponent(list.join(' Union all '))),
        Sort: (index + 1) * 10
      }
    }),
    insert: _sqlInsert,
    bottom: _sqlBottom,
    errors: errors.join('; ')
  }
}
/**
 * @description 获取excel导入参数
 * @return {Object} item   按钮信息
 * @return {Array}  data   excel数据
 */
export function getEditTableSql (verify, data, columns) {
  let btn = verify
  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') || ''
  let _sheet = btn.sheet
  let BID = data[0].$$BID || ''
  if (sessionStorage.getItem('isEditState') === 'true') {
    userName = sessionStorage.getItem('CloudUserName') || ''
    fullName = sessionStorage.getItem('CloudFullName') || ''
  }
  if (window.GLOB.externalDatabase !== null) {
    _sheet = _sheet.replace(/@db@/ig, window.GLOB.externalDatabase)
  }
  let database = _sheet.match(/(.*)\.(.*)\./ig)
  let sheet = _sheet.replace(/(.*)\.(.*)\./ig, '')
  database = database ? (database[0] || '') : ''
  let _initCustomScript = '' // 初始化脚本
  let _prevCustomScript = '' // 默认sql前执行脚本
  let _backCustomScript = '' // 默认sql后执行脚本
  if (btn.scripts && btn.intertype === 'system') {
    btn.scripts.forEach(script => {
      if (script.status === 'false') return
      if (script.position === 'init') {
        _initCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      } else if (script.position === 'front') {
        _prevCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      } else {
        _backCustomScript += `
      /* 自定义脚本 */
      ${script.sql}
      `
      }
    })
  }
  // 控制台打印数据
  let conLtext = []
  let _Ltext = data.map(item => {
    let vals = []
    let convals = []
    columns.forEach(col => {
      let val = item[col.field]
      vals.push(`'${val}'`)
      convals.push(`'${val}' as ${col.field}`)
    })
    let key = item.$$uuid
    let type = item.$type || 'upt'
    vals.push(`'${key}'`)
    vals.push(`'${type}'`)
    vals.push(`'${BID}'`)
    convals.push(`'${key}' as jskey`)
    convals.push(`'${type}' as data_type`)
    convals.push(`'${BID}' as BID`)
    conLtext.push(`Select ${convals.join(',')}`)
    return `Select ${vals.join(',')}`
  })
  let result = []
  for(let i = 0; i < _Ltext.length; i += 20) {
    result.push(_Ltext.slice(i, i + 20))
  }
  let _sql = ''
  let _sqlInsert = ''
  let _sqlBottom = ''
  if (btn.intertype === 'system') {
    let _uniquesql = ''
    if (btn.uniques && btn.uniques.length > 0) {
      btn.uniques.forEach(unique => {
        if (unique.status === 'false') return
        let _fields = unique.field.split(',')
        let _fields_ = _fields.map(_field => `a.${_field}=b.${_field}`)
        let _afields = _fields.map(_field => `a.${_field}`)
        _fields_ = _fields_.join(' and ')
        if (unique.verifyType !== 'physical') {
          _fields_ += ' and b.deleted=0'
        }
        _uniquesql += `
      /* 重复性验证 */
      Set @tbid=''
      Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${sheet} ) a group by ${unique.field} having sum(n)>1
      If @tbid!=''
      Begin
        select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 重复'
        goto aaa
      end
      Set @tbid=''
      Select top 1 @tbid=${_afields.join('+\' \'+')} from  @${sheet} a Inner join ${sheet} b on ${_fields_}
      If @tbid!=''
      Begin
        select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 与已有数据重复'
        goto aaa
      end
      `
      })
    }
    let declarefields = []
    let fields = []
    columns.forEach(col => {
      let key = col.field.toLowerCase()
      if (key === 'jskey' || key === 'bid' || key === 'data_type') return
      declarefields.push(`${col.field} ${col.datatype}`)
      fields.push(col.field)
    })
    fields = fields.join(',')
    let _insert = ''
    if (btn.default !== 'false') {
      _insert = `
      /* 默认sql */
      Insert into ${database}${sheet} (${fields},createuserid,createuser,createstaff,bid)
      Select ${fields},@userid@,@username,@fullname,@BID@ From @${sheet}
      `
    }
    _sql = `
      /* 系统生成 */
      declare @${sheet} table (${declarefields.join(',')},jskey nvarchar(50),data_type nvarchar(50),BID nvarchar(50) )
      Declare @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
      Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
      ${_initCustomScript}
      `
    _sqlInsert = `Insert into @${sheet} (${fields},jskey,data_type,BID)`
    _sqlBottom = `
      /* 默认sql */
      delete tmp_excel_in where upid=@upid@
      delete tmp_excel_in where datediff(day,createdate,getdate())>15
      ${_uniquesql}
      ${_prevCustomScript}
      ${_insert}
      ${_backCustomScript}
      Delete @${sheet}
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
    if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
      let fsql = `
      ${_sql}
      ${_sqlInsert}
      /* table数据 */
      ${conLtext.join(' Union all \n')}
      ${_sqlBottom}
      `
      fsql = fsql.replace(/\n\s{8}/ig, '\n')
      console.info(fsql)
    }
  } else { // s_sDataDictb_excelIn 云端密钥验证参数
    _sql = `
      /* 系统生成 */
      declare @${sheet} table (jskey nvarchar(50))
      Declare @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
      Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}'
      `
  }
  return {
    sql: _sql,
    lines: result.map((list, index) => {
      return {
        Ltext: window.btoa(window.encodeURIComponent(list.join(' Union all '))),
        Sort: (index + 1) * 10
      }
    }),
    insert: _sqlInsert,
    bottom: _sqlBottom
  }
}
/**
 * @description 使用系统函数时(sPC_TableData_InUpDe ),生成sql语句
 * @return {Object}  btn       按钮信息
 * @return {Object}  setting   菜单或组件数据源设置
 * @return {Array}   formdata  表单
 * @return {Object}  param     请求参数
 * @return {Array}   data      列表行数据
 * @return {Array}   columns   显示列
 * @return {Object}  tab       标签信息
 * @return {Boolean} retmsg    是否需要数据返回
 */
export function getSysDefaultSql (btn, setting, formdata, param, data, columns, tab, retmsg = false, moduleParams, getOptions) {
  let primaryId = param.ID
  let BID = param.BID
  let verify = btn.verify || {}
  let datavars = {}                 // 声明的变量,表单及显示列
  let _actionType = null
  let _callbacksql = ''
  let foreignKey = tab && tab.foreignKey ? tab.foreignKey.toLowerCase() : ''
  if (verify.default !== 'false') { // 判断是否使用默认sql
    _actionType = btn.sqlType
  }
  let _initCustomScript = '' // 初始化脚本
  let _prevCustomScript = '' // 默认sql前执行脚本
  let _backCustomScript = '' // 默认sql后执行脚本
  verify.scripts && verify.scripts.forEach(item => {
    if (item.status === 'false') return
    if (item.position === 'init') {
      _initCustomScript += `
      /* 自定义脚本 */
      ${item.sql}
      `
    } else if (item.position === 'front') {
      _prevCustomScript += `
      /* 自定义脚本 */
      ${item.sql}
      `
    } else {
      _backCustomScript += `
      /* 自定义脚本 */
      ${item.sql}
      `
    }
  })
  // 需要声明的变量集
  let _vars = ['tbid', 'errorcode', 'retmsg', 'billcode', 'bvoucher', 'fibvoucherdate', 'fiyear', 'username', 'fullname', 'modulardetailcode', 'roleid', 'mk_departmentcode', 'mk_organization', 'login_city', 'bid']
  // 主键字段
  let primaryKey = setting.primaryKey || 'id'
  // sql语句
  let _sql = ''
  let _initvars = [] // 已赋值字段集
  let _initFormfields = []
  let _initColfields = []
  let _declarefields = []
  // 获取字段键值对
  formdata && formdata.forEach(form => {
    let _key = form.key.toLowerCase()
    datavars[_key] = form.value
    if (!_initvars.includes(_key)) {
      _initvars.push(_key)
      if (form.type === 'number' || form.type === 'rate') {
        let val = form.value
        if (typeof(val) !== 'number') {
          val = parseFloat(val)
          if (isNaN(val)) {
            val = 0
          }
        }
        _initFormfields.push(`@${_key}=${val}`)
      } else if (['date', 'datemonth', 'datetime'].includes(form.type)) {
        _initFormfields.push(`@${_key}='${form.value || '1949-10-01'}'`)
      } else {
        _initFormfields.push(`@${_key}='${form.value}'`)
      }
    }
    if (!_vars.includes(_key)) {
      _vars.push(_key)
      if (form.fieldlen && form.fieldlen > 2048) {
        form.fieldlen = 'max'
      }
      let _type = `nvarchar(${form.fieldlen})`
      if (form.type.match(/date/ig)) {
        _type = 'datetime'
      } else if (form.type === 'number') {
        _type = `decimal(18,${form.fieldlen})`
      } else if (form.type === 'rate') {
        _type = `decimal(18,2)`
      }
      _declarefields.push(`@${_key} ${_type}`)
    }
  })
  if (data) {
    Object.keys(data).forEach(key => {
      data[key.toLowerCase()] = data[key]
    })
  }
  // 添加数据中字段,表单值优先(按钮不选行或多行拼接时跳过)
  if (data && !btn.$forbid && btn.Ot !== 'notRequired' && btn.Ot !== 'requiredOnce') {
    datavars = {...data, ...datavars}
    const setField = (col) => {
      if (!col.field) return
      let _key = col.field.toLowerCase()
      if (!_initvars.includes(_key)) {
        let _val = datavars.hasOwnProperty(_key) ? datavars[_key] : ''
        if (col.datatype && /^date/ig.test(col.datatype) && !_val) {
          _val = '1949-10-01'
        }
        _initvars.push(_key)
        _initColfields.push(`@${_key}='${_val}'`)
      }
      if (!_vars.includes(_key)) {
        _vars.push(_key)
        if (col.datatype) {
          _declarefields.push(`@${_key} ${col.datatype}`)
        } else {
          if (col.fieldlength && col.fieldlength > 2048) {
            col.fieldlength = 'max'
          }
          let _type = `nvarchar(${col.fieldlength || 50})`
          if (col.type === 'number') {
            let _length = col.decimal ? col.decimal : 0
            _type = `decimal(18,${_length})`
          } else if (col.type === 'picture' || col.type === 'textarea') {
            _type = `nvarchar(${col.fieldlength || 512})`
          }
          _declarefields.push(`@${_key} ${_type}`)
        }
      }
    }
    if (columns && columns.length > 0) {
      columns.forEach(col => {
        if (col.type === 'colspan' || col.type === 'old_colspan') {
          col.subcols.forEach(cell => {
            setField(cell)
          })
        } else {
          setField(col)
        }
      })
    }
  }
  // 变量声明
  _declarefields = _declarefields.join(',')
  if (_declarefields) {
    _declarefields = ',' + _declarefields
  }
  _sql = `/* 系统生成 */
      Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50),@RoleID nvarchar(512),@mk_departmentcode nvarchar(50),@mk_organization nvarchar(50),@login_city nvarchar(50),@bid nvarchar(50),@ModularDetailCode nvarchar(50)${_declarefields}
    `
  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') || ''
  }
  // 初始化凭证及用户信息字段
  _sql += `
      /* 凭证及用户信息初始化赋值 */
      select @BVoucher='',@FIBVoucherDate='',@FiYear='',@ErrorCode='',@retmsg='',@UserName='${userName}', @FullName='${fullName}', @RoleID='${RoleID}', @mk_departmentcode='${departmentcode}', @mk_organization='${organization}', @login_city='${city}', @BillCode='', @ModularDetailCode=''
      `
  // 表单变量赋值
  if (_initFormfields.length > 0) {
    _sql += `
      /* 表单变量赋值 */
      select ${_initFormfields.join(',')}
      `
  }
  // 显示列变量赋值
  if (_initColfields.length > 0) {
    _sql += `
      /* 显示列变量赋值 */
      select ${_initColfields.join(',')}
      `
  }
  // 去除禁用的验证
  if (verify.contrasts) {
    verify.contrasts = verify.contrasts.filter(item => item.status !== 'false')
  }
  if (verify.uniques) {
    verify.uniques = verify.uniques.filter(item => item.status !== 'false')
  }
  if (verify.customverifys) {
    verify.customverifys = verify.customverifys.filter(item => item.status !== 'false')
  }
  if (verify.billcodes) {
    verify.billcodes = verify.billcodes.filter(item => item.status !== 'false')
  }
  if (retmsg) {
    _callbacksql = _sql
  }
  if (_initCustomScript) {
    _sql += _initCustomScript
  }
  // 启用账期验证
  if (verify.accountdate === 'true') {
    let orgcode = `''`
    let date = `''`
    if (verify.accountfield && _initvars.includes(verify.accountfield.toLowerCase())) {
      orgcode = '@' + verify.accountfield
    }
    if (verify.voucherdate && _initvars.includes(verify.voucherdate.toLowerCase())) {
      date = '@' + verify.voucherdate
    }
    _sql += `
      /* 账期验证 */
      exec s_FIBVoucherDateCheck @OrgCode=${orgcode},@FIBVoucherDate=${date},@ErrorCode=@ErrorCode OUTPUT,@retmsg=@retmsg OUTPUT
      if @ErrorCode!=''
        GOTO aaa
      `
  }
  // 失效验证,添加数据时不用
  if (btn.sqlType !== 'insert' && btn.Ot !== 'notRequired' && verify.invalid === 'true' && setting.dataresource) {
    let datasource = setting.dataresource
    let customScript = setting.customScript || ''
    let search = moduleParams ? moduleParams.search : null
    let orderBy = moduleParams ? moduleParams.orderBy : setting.order
    if (/\s/.test(datasource) && !/tb$/.test(datasource)) { // 拼接别名
      datasource = '(' + datasource + ') tb'
    }
    if (getOptions && (setting.queryType === 'statistics' || customScript)) {
      let allSearch = getOptions(search)
      let regoptions = allSearch.map(item => {
        return {
          reg: new RegExp('@' + item.key + '@', 'ig'),
          value: `'${item.value}'`
        }
      })
      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
      }, {
        reg: new RegExp('@pageSize@', 'ig'),
        value: 999999
      }, {
        reg: new RegExp('@pageIndex@', 'ig'),
        value: 1
      })
      regoptions.forEach(item => {
        datasource = datasource.replace(item.reg, item.value)
        customScript = customScript.replace(item.reg, item.value)
      })
    }
    if (customScript) {
      _sql += `
      /* 数据源自定义脚本,请注意变量定义是否重复 */
      ${customScript}
      `
    }
    if (btn.Ot === 'requiredOnce') {
      _sql += `
      /* 失效验证 */
      select @tbid='', @ErrorCode='',@retmsg=''
      select @tbid='X' from ${datasource} right join (select ID from  dbo.SplitComma(@ID@)) sp
      on tb.id =sp.id where tb.id is null
      If @tbid!=''
      Begin
        select @ErrorCode='E',@retmsg='数据已失效'
        goto aaa
      end
      `
    } else {
      _sql += `
      /* 失效验证 */
      select @tbid='', @ErrorCode='',@retmsg=''
      select @tbid=${primaryKey} from ${datasource} where ${primaryKey}=@ID@
      If @tbid=''
      Begin
        select @ErrorCode='E',@retmsg='数据已失效'
        goto aaa
      end
      `
    }
  }
  // 比较验证
  if (verify.contrasts && verify.contrasts.length > 0) {
    verify.contrasts.forEach(item => {
      _sql += `
      /* 比较验证 */
      If ${item.frontfield} ${item.operator} ${item.backfield}
      Begin
        select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
          goto aaa
      end
      `
    })
  }
  // 自定义验证
  verify.customverifys && verify.customverifys.forEach(item => {
    _sql += `
      /* 自定义验证 */
      select @tbid='', @ErrorCode='',@retmsg=''
      select top 1 @tbid='X' from (${item.sql}) a
      If @tbid ${item.result === 'true' ? '!=' : '='}''
      Begin
        select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
        goto aaa
      end
      `
  })
  // 单号生成,使用上级id(BID)或列表数据,声明变量(检验)
  let _billcodesSql  = ''
  if (formdata && verify.billcodes && verify.billcodes.length > 0) {
    let keys = formdata.map(item => item.key.toLowerCase()) // 表单字段
    verify.billcodes.forEach(item => {
      let _key = item.field.toLowerCase()
      let _linkKey = item.linkField ? item.linkField.toLowerCase() : ''
      if (!keys.includes(_key)) return // 表单中不含单号生成字段
      let _ModularDetailCode = ''
      let _lpline = ''
      if (item.TypeCharOne === 'Lp') {
        if (_linkKey === 'bid' && BID) { // 替换bid
          _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@BID@,48)`
        } else {
          _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@${_linkKey},48)`
        }
        _ModularDetailCode = '@ModularDetailCode'
      } else if (item.TypeCharOne === 'BN') {
        let _val = ''
        if (_linkKey === 'bid' && BID) { // 替换bid
          _val = BID
        } else if (data && data.hasOwnProperty(_linkKey)) {
          _val = data[_linkKey]
        }
        _ModularDetailCode = `'${item.TypeCharOne + _val}'`
      } else {
        _ModularDetailCode = `'${item.ModularDetailCode}'`
      }
      let _declare = ''
      if (!_vars.includes(_key)) {
        _declare = `Declare @${_key} nvarchar(50)`
        _vars.push(_key)
      }
      _billcodesSql += `
      /* 单号生成 */
      ${_declare}
      select @BillCode='', @${_key}='', @ModularDetailCode=''
      ${_lpline}
      exec s_get_BillCode
        @ModularDetailCode=${_ModularDetailCode},
        @Type=${item.Type},
        @TypeCharOne='${item.TypeCharOne}',
        @TypeCharTwo ='${item.TypeCharTwo}',
        @BillCode =@BillCode output,
        @ErrorCode =@ErrorCode output,
        @retmsg=@retmsg output
      if @ErrorCode!=''
        goto aaa
      set @${_key}=@BillCode
      `
    })
    if (_actionType !== 'insertOrUpdate') {
      _sql += _billcodesSql
    }
  }
  // 唯一性验证,必须存在表单(表单存在时,主键均为单值),必须填写数据源,多行拼接时不可用
  if (formdata && verify.uniques && verify.uniques.length > 0 && btn.Ot !== 'requiredOnce') {
    verify.uniques.forEach(item => {
      let _fieldValue = []                     // 表单键值对field=value
      let _value = []                          // 表单值,用于错误提示
      let _labels = item.fieldlabel.split(',') // 表单提示文字
      let arr = [] // 验证主键
      item.field.split(',').forEach((_field, index) => {
        let _key = _field.toLowerCase()
        let _val = datavars[_key] !== undefined ? datavars[_key] : ''
        let _fval = `'${_val}'`
        if (_key === 'bid' && !datavars.bid) { // 表单中没有bid则使用系统bid变量
          _fval = '@BID@'
        }
        if (_key === 'bid' && foreignKey) {
          arr.push(foreignKey)
          _fieldValue.push(`${foreignKey}=${_fval}`)
        } else {
          arr.push(_key)
          _fieldValue.push(`${_key}=${_fval}`)
        }
        _value.push(`${_labels[index] || ''}:${_val || ''}`)
      })
      let _verifyType = ''
      if (item.verifyType === 'logic') {
        _verifyType = ' and deleted=0'
      }
      if (!arr.includes(primaryKey.toLowerCase())) {
        _fieldValue.push(`${primaryKey} !='${primaryId}'`)
      }
      _sql += `
      /* 唯一性验证 */
      select @tbid='', @ErrorCode='',@retmsg=''
      select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')}${_verifyType}
      If @tbid!=''
      Begin
        select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 已存在'
        goto aaa
      end
      `
    })
  } else if (verify.uniques && verify.uniques.length > 0 && btn.Ot === 'requiredOnce' && setting.dataresource) {
    let datasource = setting.dataresource
    if (/\s/.test(datasource)) { // 拼接别名
      if (!/tb$/.test(datasource)) {
        datasource = '(' + datasource + ') tb'
      }
    } else {
      datasource = datasource + ' tb'
    }
    if (setting.customScript) {
      _sql += `
      /* 数据源自定义脚本,请注意变量定义是否重复 */
      ${setting.customScript}
      `
    }
    verify.uniques.forEach(item => {
      _sql += `
      /* 同类数据验证 */
      Set @tbid=''
      Select top 1 @tbid='X' from (select distinct ${item.field},1 as n from ${datasource} inner join (select ID from  dbo.SplitComma(@ID@)) sp on tb.${primaryKey}=sp.ID ) a having sum(n)>1
      If @tbid!=''
      Begin
        Set @ErrorCode='E' Set @retmsg='${item.fieldlabel} 值不唯一'
        goto aaa
      end
      `
    })
  }
  let hasvoucher = false
  // 凭证-显示列中选取,必须选行
  if (verify.voucher && verify.voucher.enabled && data) {
    let _voucher = verify.voucher
    hasvoucher = true
    _sql += `
      /* 创建凭证 */
      exec s_BVoucher_Create
        @Bill ='${data[_voucher.linkField.toLowerCase()]}',
        @BVoucherType ='${_voucher.BVoucherType}',
        @VoucherTypeOne ='${_voucher.VoucherTypeOne}',
        @VoucherTypeTwo ='${_voucher.VoucherTypeTwo}',
        @Type =${_voucher.Type},
        @UserID=@UserID@,
        @Username=@Username,
        @FullName=@FullName,
        @BVoucher =@BVoucher OUTPUT ,
        @FIBVoucherDate =@FIBVoucherDate OUTPUT ,
        @FiYear =@FiYear OUTPUT ,
        @ErrorCode =@ErrorCode OUTPUT,
        @retmsg=@retmsg OUTPUT
      if @ErrorCode!=''
        GOTO aaa
      `
  }
  let _insertsql = ''
  if (_actionType === 'insert' || _actionType === 'insertOrUpdate') { // 添加语句
    let keys = []
    let values = []
    formdata.forEach(item => {
      if (item.writein === false) return
      let _key = item.key.toLowerCase()
      keys.push(_key)
      values.push('@' + _key)
    })
    if (!keys.includes(primaryKey.toLowerCase())) {
      keys.push(primaryKey.toLowerCase())
      values.push('\'' + primaryId + '\'')
    }
    if (!keys.includes('createuserid')) {
      keys.push('createuserid')
      values.push('@userid@')
    }
    if (!keys.includes('createuser')) {
      keys.push('createuser')
      values.push('@username')
    }
    if (!keys.includes('createstaff')) {
      keys.push('createstaff')
      values.push('@fullname')
    }
    if (!keys.includes('bid')) {
      if (foreignKey && !keys.includes(foreignKey)) {
        keys.push(foreignKey)
      } else {
        keys.push('bid')
      }
      values.push('@BID@')
    } else if (foreignKey && !keys.includes(foreignKey)) {
      keys.push(foreignKey)
      values.push('@BID@')
    }
    keys = keys.join(',')
    values = values.join(',')
    _insertsql = `insert into ${btn.sql} (${keys}) select ${values};`
  }
  let _updatesql = ''
  if (_actionType === 'update' || _actionType === 'audit' || _actionType === 'insertOrUpdate') { // 修改语句
    let _form = []
    let _arr = []
    formdata.forEach(item => {
      if (item.writein === false) return
      let _key = item.key.toLowerCase()
      _arr.push(_key)
      _form.push(_key + '=@' + _key)
    })
    if (_actionType === 'audit') {
      if (!_arr.includes('submitdate')) {
        _form.push('submitdate=getdate()')
      }
      if (!_arr.includes('submituserid')) {
        _form.push('submituserid=@userid@')
      }
      if (!_arr.includes('submituser')) {
        _form.push('submituser=@username')
      }
    } else {
      if (!_arr.includes('modifydate')) {
        _form.push('modifydate=getdate()')
      }
      if (!_arr.includes('modifyuser')) {
        _form.push('modifyuser=@username')
      }
      if (!_arr.includes('modifyuserid')) {
        _form.push('modifyuserid=@userid@')
      }
    }
    if (hasvoucher) {
      if (!_arr.includes('bvoucher')) {
        _form.push('BVoucher=@BVoucher')
      }
      if (!_arr.includes('fibvoucherdate')) {
        _form.push('FIBVoucherDate=@FIBVoucherDate')
      }
      if (!_arr.includes('fiyear')) {
        _form.push('FiYear=@FiYear')
      }
    }
    _form = _form.join(',')
    let _ID = '=@ID@'
    if (btn.Ot === 'requiredOnce') {
      _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
    }
    _updatesql = `update ${btn.sql} set ${_form} where ${primaryKey}${_ID};`
  }
  if (_prevCustomScript) {
    _sql += _prevCustomScript
  }
  // 添加、修改、逻辑删除、物理删除
  if (_actionType === 'insert') {
    _sql += `
      /* 默认sql */
      ${_insertsql}`
  } else if (_actionType === 'update' || _actionType === 'audit') {
    _sql += `
      /* 默认sql */
      ${_updatesql}`
  } else if (_actionType === 'LogicDelete') { // 逻辑删除
    let _ID = '=@ID@'
    if (btn.Ot === 'requiredOnce') {
      _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
    }
    _sql += `
      /* 默认sql */
      update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuser=@username,modifyuserid=@userid@ where ${primaryKey}${_ID};`
  } else if (_actionType === 'delete') {      // 物理删除
    let _msg = ''
    if (data && columns && columns.length > 0) {
      let _index = 0
      columns.forEach(col => {
        if (col.Hide !== 'true' && col.type !== 'colspan' && col.type !== 'old_colspan' && _index < 4) {
          _msg += col.label + '=' + data[col.field] + ','
          _index++
        }
      })
    }
    let _ID = '=@ID@'
    if (btn.Ot === 'requiredOnce') {
      _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
    }
    _sql += `
      /* 默认sql */
      insert into snote (remark,createuserid,CreateUser,CreateStaff) select left('删除表:${btn.sql} 数据: ${_msg}${primaryKey}='+@ID@,200),@userid@,@username,@fullname
      delete ${btn.sql} where ${primaryKey}${_ID};`
  } else if (_actionType === 'insertOrUpdate') {
    _sql += `
      /* 默认sql */
      select @tbid=''
      select @tbid='X' from ${btn.sql} where ${primaryKey}=@ID@
      if @tbid=''
        begin
        ${_billcodesSql}
        ${_insertsql}
        end
      else
        begin
        ${_updatesql}
        end
    `
  }
  if (_backCustomScript) {
    _sql += _backCustomScript
  }
  if (retmsg) {
    _sql += `
      aaa: if @ErrorCode!=''
      insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@`
  } else if (btn.output) {
    _sql += `
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg,${btn.output} as mk_b_id`
  } else {
    _sql += `
      aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
  }
  if (window.GLOB.debugger === true || (window.debugger === true && options.sysType !== 'cloud')) {
    // _sql = _sql.replace(/\n\s{8}/ig, '\n')
    console.info(_sql)
  }
  if (retmsg) {
    return {
      sql: _sql,
      callbacksql: _callbacksql
    }
  } else {
    return _sql
  }
}
/**
 * @description 获取标记信息
 */
export function getMark (marks, record, style = {}) {
  let icon = null
  let color = null
  let position = null
  style = JSON.parse(JSON.stringify(style))
  marks.some(mark => {
    let originVal = record[mark.field[0]] + ''
    let contrastVal = ''
    let result = false
    if (mark.field[1] === 'static') {
      contrastVal = mark.contrastValue + ''
    } else {
      contrastVal = record[mark.field[2]] + ''
    }
    if (mark.match === '=') {
      result = originVal === contrastVal
    } else if (mark.match === '!=') {
      result = originVal !== contrastVal
    } else if (mark.match === 'like') {
      result = originVal.indexOf(contrastVal) > -1
    } else if (mark.match === '>') {
      result = parseFloat(originVal) > parseFloat(contrastVal)
    } else if (mark.match === '<') {
      result = parseFloat(originVal) < parseFloat(contrastVal)
    }
    if (!result) return false
    let type = mark.signType[0]
    if (type === 'font') {
      style.color = mark.color
    } else if (type === 'background') {
      style.background = mark.color
      if (mark.fontColor) {
        style.color = mark.fontColor
      }
    } else if (type === 'underline') {
      style.textDecoration = 'underline'
      style.color = mark.color
    } else if (type === 'line-through') {
      style.textDecoration = 'line-through'
      style.color = mark.color
    } else if (type.indexOf('icon') > -1) {
      icon = mark.signType[mark.signType.length - 1]
      color = mark.color
      if (type === 'iconfront' || mark.signType[1] === 'front') {
        position = 'front'
      } else {
        position = 'back'
      }
    }
    return true
  })
  return {
    style,
    icon,
    color,
    position
  }
}
/**
 * @description 生成替换函数列表
 */
export function setGLOBFuncs () {
  window.GLOB.funcs = []
  if (!window.GLOB.WebSql && !window.GLOB.IndexDB) {
    return
  }
  if (window.GLOB.WebSql) {
    window.GLOB.WebSql.transaction(tx => {
      tx.executeSql("SELECT * FROM FUNCS", [], (tx, results) => {
        let rows = results.rows
        if (!rows || rows.length === 0) return
        for (let i = 0; i < rows.length; i++) {
          window.GLOB.funcs.push({
            func_code: rows[i].func_code,
            key_sql: window.decodeURIComponent(window.atob(rows[i].key_sql))
          })
        }
      })
    })
  } else {
    let objectStore = window.GLOB.IndexDB.transaction('funcs').objectStore('funcs')
    objectStore.openCursor().onsuccess = (event) => {
      let cursor = event.target.result
      if (cursor) {
        window.GLOB.funcs.push({
          func_code: cursor.value.func_code,
          key_sql: window.decodeURIComponent(window.atob(cursor.value.key_sql))
        })
        cursor.continue()
      }
    }
  }
}
/**
 * @description 创建存储过程类
 */
export class FuncUtils {
  /**
   * @description 删除存储过程sql
   * @return {String} name 存储过程名称
   */
  static dropfunc (name) {
    return `IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('${name}') AND type in (N'P', N'PC'))  mdrpk PROCEDURE ${name}`
  }
  /**
   * @description 创建页面存储过程
   * @return {String}
   */
  static getTableFunc (param, menu, config) {
    let form = ''
    let formParam = ''
    let _vars = ['bid', 'pageindex', 'pagesize', 'ordercol', 'ordertype', 'exceltype', 'septmenuno', 'lang', 'debug', 'loginuid', 'sessionuid', 'userid', 'errorcode', 'retmsg']
    let _columns = []
    let primaryKey = config.setting.primaryKey || 'ID'
    if (!_vars.includes(primaryKey.toLowerCase())) {
      _vars.push(primaryKey.toLowerCase())
      formParam = `mchr13k@${primaryKey} nvarchar(50)='',`
    }
    if (config.search && config.search.length > 0) {
      let _fields = new Map()
      config.search.forEach(item => {
        if (item.field) {
          let type = ''
          if (item.type.match(/date/ig)) {
            type = 'datetime=null'
          } else {
            type = 'nvarchar(50)=\'\''
          }
          item.field.split(',').forEach(cell => {
            let _f = cell
            if (_fields.has(cell)) {
              _f = _f + '1'
            }
            _fields.set(cell, true)
            if (!_vars.includes(_f.toLowerCase())) {
              _vars.push(_f.toLowerCase())
              formParam = formParam + `mchr13k@${_f} ${type},`
            }
          })
        }
      })
    }
    if (config.columns && config.columns.length > 0) {
      config.columns.forEach(item => {
        if (item.field) {
          _columns.push(`${item.field} as ${item.label}`)
        }
      })
      let _lineIndex = '0000' + (lindex + 1) + '0'
      _lineIndex = _lineIndex.substring(_lineIndex.length - 6)
      vals.push(`'${upId + _lineIndex}'`)
      vals.push(`'${BID}'`)
      if (lindex < 40) {
        convals.push(`'${upId + _lineIndex}' as jskey`)
        convals.push(`'${BID}' as BID`)
        conLtext.push(`Select ${convals.join(',')}`)
      }
      return `Select ${vals.join(',')}`
    })
    let result = []
    for(let i = 0; i < _Ltext.length; i += 20) {
      result.push(_Ltext.slice(i, i + 20))
      form = `
        declare @dc table (${_columns.join(',')})
        @tableid ='${menu.MenuID}'
      `
    }
    let _sql = ''
    let _sqlInsert = ''
    let _sqlBottom = ''
    let Ltext = `create proc ${param.innerFunc}
    ( /*${menu.MenuName}*/
    @appkey nvarchar(50)='',
    @BID nvarchar(50)='',${formParam}
    @PageIndex nvarchar(50)='',
    @PageSize nvarchar(50)='',
    @OrderCol nvarchar(50)='',
    @OrderType nvarchar(50)='',
    @exceltype nvarchar(50)='',
    @sEPTMenuNo nvarchar(50)='${menu.MenuNo}',
    @lang nvarchar(50)='',
    @debug nvarchar(50)='',
    @LoginUID nvarchar(50)='',
    @SessionUid nvarchar(50)='',
    @UserID nvarchar(50),
    @ErrorCode nvarchar(50) out,
    @retmsg nvarchar(4000) out
    )
    as
    begin
    declare  @BegindateTest datetime,@EnddateTest datetime
    select  @BegindateTest=getdate()
    set @ErrorCode=''
    set @retmsg=''
    BEGIN TRY
      /*事务操作*/
      BEGIN TRAN
        /*具体业务操作*/
        /*
        select top 10 * from sProcExcep order by id desc
        declare @UserName  nvarchar(50),@FullName nvarchar(50)
        select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
        ${form}
        if 1=2
        begin
          set @ErrorCode='E'
          set @retmsg='在此写报错'
          goto GOTO_RETURN
        end
        insert into sNote (remark,createuserid,CreateUser,CreateStaff)
        select '在此写日志',@UserID,@UserName,@FullName
        */
      COMMIT TRAN
      SET NOCOUNT ON
      RETURN
    END TRY
    BEGIN CATCH
      /*错误处理*/
      ROLLBACK TRAN
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
      /*把自定义的友好的错误信息提示加上*/
      set @ErrorCode=cast(ERROR_NUMBER() as nvarchar(50))
      SET @retmsg=ERROR_MESSAGE();
      SELECT @ErrorMessage=ERROR_MESSAGE(),
        @ErrorSeverity=ERROR_SEVERITY(),
        @ErrorState=ERROR_STATE();
      RAISERROR(@ErrorMessage, /*-- Message text.*/
        @ErrorSeverity, /*-- Severity.*/
        @ErrorState  /*-- State.*/
      );
    END CATCH
    GOTO_RETURN:
      ROLLBACK TRAN
    END`
    if (item.intertype === 'system') {
      let _uniquesql = ''
      if (btn.uniques && btn.uniques.length > 0) {
        btn.uniques.forEach(unique => {
          if (unique.status === 'false') return
    Ltext = Ltext.replace(/\n\s{4}/ig, 'mchr13k')
          let _fields = unique.field.split(',')
          let _fields_ = _fields.map(_field => `a.${_field}=b.${_field}`)
          let _afields = _fields.map(_field => `a.${_field}`)
          _fields_ = _fields_.join(' and ')
    return Ltext
  }
          if (unique.verifyType !== 'physical') {
            _fields_ += ' and b.deleted=0'
  /**
   * @description 创建存储过程
   * @return {String}
   */
  static getfunc (param, btn, menu, config) {
    let form = ''
    let formParam = ''
    let _vars = ['bid', 'septmenuno', 'lang', 'debug', 'loginuid', 'sessionuid', 'userid', 'errorcode', 'retmsg']
    let columns = config.columns
    let primaryKey = config.setting.primaryKey || 'ID'
    if (!_vars.includes(primaryKey.toLowerCase())) {
      _vars.push(primaryKey.toLowerCase())
      let _type = '50'
      if (btn.Ot === 'requiredOnce') { // 多行拼接时,主键设为max
        _type = 'max'
      }
      formParam = `mchr13k@${primaryKey} nvarchar(${_type})='',`
    }
    if (param.fields && param.fields.length > 0) {
      let _fields = []
      param.fields.forEach(item => {
        if (item.field) {
          let type = ''
          if (item.type.match(/date/ig)) {
            type = 'datetime=null'
          } else if (item.type === 'number') {
            type = `decimal(18,${item.decimal})=0`
          } else if (item.type === 'rate') {
            type = `decimal(18,2)=0`
          } else {
            type = 'nvarchar(50)=\'\''
          }
          _uniquesql += `
        /* 重复性验证 */
        Set @tbid=''
        Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${sheet} ) a group by ${unique.field} having sum(n)>1
          if (!_vars.includes(item.field.toLowerCase())) {
            _vars.push(item.field.toLowerCase())
            formParam = formParam + `mchr13k@${item.field} ${type},`
          }
          _fields.push(item.field)
        }
      })
      let field1 = _fields.join(',')
      let field2 = _fields.join(',@')
      let field3 = _fields.map(cell => {
        return cell + '=@' + cell
      })
      field2 = field2 ? '@' + field2 : ''
      field3 = field3.join(',')
      form = `
        insert into ${param.name} (${field1},createuserid) select ${field2},@UserID
        
        update ${param.name} set ${field3},modifydate=getdate(),modifyuser=@username,modifyuserid=@UserID
      `
    } else if (btn.OpenType === 'prompt' || btn.OpenType === 'exec') {
      form = `
        update ${param.name} set ModifyDate=getdate(),ModifyUserID=@UserID where ${primaryKey}=@${primaryKey}
      `
    }
    if (columns) {
      let _col = []
      let _field = []
      columns.forEach(col => {
        if (col.field) {
          if (col.type === 'number') {
            _col.push(col.field + ' decimal(18,2)')
          } else {
            _col.push(col.field + ' nvarchar(50)')
          }
          _field.push(col.field)
        }
      })
      _col = _col.join(',')
      _field = _field.join(',')
      form = form + `
        declare @dc table (${_col})
        insert into @dc (${_field})
        @tableid ='${menu.MenuID}'
      `
    }
    // 打印自定义模板字段提示
    let _printRemark = ''
    if (btn.funcType === 'print') {
      _printRemark = '/* 自定义数据打印模板时,请使用TemplateID字段 */'
    }
    let Ltext = `create proc ${param.funcName}
    ( /*${menu.MenuName}  ${btn.label}*/
    @appkey nvarchar(50)='',
    @BID nvarchar(50)='',${formParam}
    @sEPTMenuNo nvarchar(50)='${param.menuNo}',
    @lang nvarchar(50)='',
    @debug nvarchar(50)='',
    @LoginUID nvarchar(50)='',
    @SessionUid nvarchar(50)='',
    @UserID nvarchar(50),
    @ErrorCode nvarchar(50) out,
    @retmsg nvarchar(4000) out
    )
    as
    begin
    declare  @BegindateTest datetime,@EnddateTest datetime
    select  @BegindateTest=getdate()
    set @ErrorCode=''
    set @retmsg=''
    BEGIN TRY
      /*事务操作*/
      BEGIN TRAN
        /*具体业务操作*/
        ${_printRemark}
        /*
        select top 10 * from sProcExcep order by id desc
        declare @UserName  nvarchar(50),@FullName nvarchar(50)
        select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
        ${form}
        if 1=2
        begin
          set @ErrorCode='E'
          set @retmsg='在此写报错'
          goto GOTO_RETURN
        end
        insert into sNote (remark,createuserid,CreateUser,CreateStaff)
        select '在此写日志',@UserID,@UserName,@FullName
        */
      COMMIT TRAN
      SET NOCOUNT ON
      RETURN
    END TRY
    BEGIN CATCH
      /*错误处理*/
      ROLLBACK TRAN
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
      /*把自定义的友好的错误信息提示加上*/
      set @ErrorCode=cast(ERROR_NUMBER() as nvarchar(50))
      SET @retmsg=ERROR_MESSAGE();
      SELECT @ErrorMessage=ERROR_MESSAGE(),
        @ErrorSeverity=ERROR_SEVERITY(),
        @ErrorState=ERROR_STATE();
      RAISERROR(@ErrorMessage, /*-- Message text.*/
        @ErrorSeverity, /*-- Severity.*/
        @ErrorState  /*-- State.*/
      );
    END CATCH
    GOTO_RETURN:
      ROLLBACK TRAN
    END`
    Ltext = Ltext.replace(/\n\s{4}/ig, 'mchr13k')
    return Ltext
  }
  /**
   * @description 创建导入存储过程
   * @return {String}
   */
  static getexcelInfunc (param, btn, menu) {
    let _verify = btn.verify
    let _uniquesql = ''
    if (_verify.uniques && _verify.uniques.length > 0) {
      _verify.uniques.forEach(unique => {
        if (unique.status === 'false') return
        let _fields = unique.field.split(',')
        let _fields_ = _fields.map(_field => {
          return `a.${_field}=b.${_field}`
        })
        _fields_ = _fields_.join(' and ')
        if (unique.verifyType !== 'physical') {
          _fields_ += ' and b.deleted=0'
        }
        _uniquesql += `
        Set @tbid=''
        Select top 1 @tbid=${_fields.join('+\' \'+')} from (select 1 as n,${unique.field} from @${btn.sheet} ) a group by ${unique.field} having sum(n)>1
        If @tbid!=''
        Begin
          select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 重复'
          goto aaa
        end
        Set @tbid=''
        Select top 1 @tbid=${_afields.join('+\' \'+')} from  @${sheet} a Inner join ${sheet} b on ${_fields_}
        Select top 1 @tbid=${_fields.join('+\' \'+')} from  @${btn.sheet} a
        Inner join ${btn.sheet} b on ${_fields_}
        If @tbid!=''
        Begin
          select @ErrorCode='${unique.errorCode}',@retmsg=@tbid+' 与已有数据重复'
          goto aaa
        end
        `
        })
      }
      let declarefields = []
      let fields = []
      btn.columns.forEach(col => {
        if (col.import === 'false') return
        if (col.type === 'date') {
          declarefields.push(`${col.Column} Nvarchar(50)`)
        } else {
          declarefields.push(`${col.Column} ${col.type}`)
        }
        fields.push(col.Column)
      })
      fields = fields.join(',')
      let _insert = ''
      if (btn.default !== 'false') {
        _insert = `
        /* 默认sql */
        Insert into ${database}${sheet} (${fields},createuserid,createuser,createstaff,bid)
        Select ${fields},@userid@,@username,@fullname,@BID@ From @${sheet}
        `
      if (_uniquesql) {
        _uniquesql = `
        Declare @tbid Nvarchar(512)
        ${_uniquesql}`
      }
    }
      _sql = `
        /* 系统生成 */
        declare @${sheet} table (${declarefields.join(',')},jskey nvarchar(50),BID nvarchar(50) )
        Declare @UserName nvarchar(50),@FullName nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
        Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}'
        ${_initCustomScript}
        `
      _sqlInsert = `Insert into @${sheet} (${fields},jskey,BID)`
      _sqlBottom = `
        /* 默认sql */
        delete tmp_excel_in where upid=@upid@
        delete tmp_excel_in where datediff(day,createdate,getdate())>15
        ${_uniquesql}
        ${_prevCustomScript}
        ${_insert}
        ${_backCustomScript}
        Delete @${sheet}
        aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
    let declarefields = []
    let fields = []
      if ((window.GLOB.systemType !== 'production' && options.sysType !== 'cloud') || window.debugger === true) {
        let fsql = `
    _verify.columns.forEach(col => {
      declarefields.push(`${col.Column} ${col.type}`)
      fields.push(col.Column)
    })
    fields = fields.join(',')
    let _sql = `declare @${btn.sheet} table (${declarefields.join(',')},jskey nvarchar(50))
      Declare @UserName nvarchar(50),@FullName nvarchar(50)
      select @UserName=UserName,@FullName=FullName from SUsers where UID=@UserID
      Insert into @${btn.sheet} (${fields},jskey)
      exec s_KeyWords_Replace
      @LText=@LText, @BID=@BID,@LoginUID=@LoginUID,@SessionUid=@SessionUid,@UserID=@UserID,@ID=@ID
      ${_uniquesql}
      Insert into ${btn.sheet} (${fields},createuserid,createuser,createstaff,bid)
      Select ${fields},@userid,@username,@fullname,@BID From @${btn.sheet}
      Delete @${btn.sheet}`
    let Ltext = `create proc ${param.funcName}
    ( /*${menu.MenuName}  ${btn.label}*/
      @appkey nvarchar(50)='',
      @ID nvarchar(50)='',
      @BID nvarchar(50)='',
      @Ltext nvarchar(max)='',
      @sEPTMenuNo nvarchar(50)='${param.menuNo}',
      @secretkey nvarchar(50)='',
      @timestamp nvarchar(50)='',
      @lang nvarchar(50)='',
      @LoginUID nvarchar(50)='',
      @SessionUid nvarchar(50)='',
      @UserID nvarchar(50),
      @ErrorCode nvarchar(50) out,
      @retmsg nvarchar(4000) out
    )
    as
    begin
    declare @BegindateTest datetime,@EnddateTest datetime
    select @BegindateTest=getdate()
    set @ErrorCode=''
    set @retmsg=''
    BEGIN TRY
      /*事务操作*/
      BEGIN TRAN
        /*具体业务操作*/
        /*
        ${_sql}
        ${_sqlInsert}
        */
        
        /* excel数据(前40条) */
        ${conLtext.join(' Union all ')}
        ${_sqlBottom}
        `
        fsql = fsql.replace(/\n\s{8}/ig, '\n')
        console.info(fsql)
      }
    } else { // s_sDataDictb_excelIn 云端密钥验证参数
      _sql = `
        /* 系统生成 */
        declare @${sheet} table (jskey nvarchar(50))
        Declare @UserName nvarchar(50),@FullName nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@tbid Nvarchar(512)
        Select  @ErrorCode='', @retmsg='', @UserName='${userName}', @FullName='${fullName}'
        `
    }
    return {
      sql: _sql,
      lines: result.map((list, index) => {
        return {
          Ltext: window.btoa(window.encodeURIComponent(list.join(' Union all '))),
          Sort: (index + 1) * 10
        }
      }),
      insert: _sqlInsert,
      bottom: _sqlBottom,
      errors: errors.join('; ')
    }
  }
  /**
   * @description 使用系统函数时(sPC_TableData_InUpDe ),生成sql语句
   * @return {String} type   执行类型
   * @return {String} table  表名
   */
  static getSysDefaultSql (btn, setting, formdata, param, data, columns, tab, retmsg) {
    let primaryId = param.ID
    let BID = param.BID
    let verify = btn.verify || {}
    let datavars = {}                 // 声明的变量,表单及显示列
    let _actionType = null
    let appkey = window.GLOB.appkey || ''
    let sessionUid = localStorage.getItem('SessionUid') || ''
    if (verify.default !== 'false') { // 判断是否使用默认sql
      _actionType = btn.sqlType
    }
    let _initCustomScript = '' // 初始化脚本
    let _prevCustomScript = '' // 默认sql前执行脚本
    let _backCustomScript = '' // 默认sql后执行脚本
    verify.scripts && verify.scripts.forEach(item => {
      if (item.status === 'false') return
      if (item.position === 'init') {
        _initCustomScript += `
        /* 自定义脚本 */
        ${item.sql}
        `
      } else if (item.position === 'front') {
        _prevCustomScript += `
        /* 自定义脚本 */
        ${item.sql}
        `
      } else {
        _backCustomScript += `
        /* 自定义脚本 */
        ${item.sql}
        `
      }
    })
    // 需要声明的变量集
    let _vars = ['tbid', 'errorcode', 'retmsg', 'billcode', 'bvoucher', 'fibvoucherdate', 'fiyear', 'username', 'fullname', 'modulardetailcode']
    // 主键字段
    let primaryKey = setting.primaryKey || 'id'
    // sql语句
    let _sql = ''
    let _initvars = [] // 已赋值字段集
    let _initFormfields = []
    let _initColfields = []
    let _declarefields = []
    // 获取字段键值对
    formdata && formdata.forEach(form => {
      if (form.type === 'text') { // 特殊字段替换
        form.value = form.value.replace(/^(\s*)@appkey@(\s*)$/ig, appkey)
        form.value = form.value.replace(/^(\s*)@SessionUid@(\s*)$/ig, sessionUid)
        form.value = form.value.replace(/^(\s*)@bid@(\s*)$/ig, BID)
      }
      let _key = form.key.toLowerCase()
      datavars[_key] = form.value
      if (!_initvars.includes(_key)) {
        _initvars.push(_key)
        if (form.type === 'number') {
          let val = form.value
          if (typeof(val) !== 'number') {
            val = parseFloat(val)
            if (isNaN(val)) {
              val = 0
            }
          }
          _initFormfields.push(`@${_key}=${val}`)
        } else {
          _initFormfields.push(`@${_key}='${form.value}'`)
        }
      }
      COMMIT TRAN
      SET NOCOUNT ON
      RETURN
    END TRY
    BEGIN CATCH
      /*错误处理*/
      ROLLBACK TRAN
      DECLARE @ErrorMessage NVARCHAR(4000);
      DECLARE @ErrorSeverity INT;
      DECLARE @ErrorState INT;
      
      if (!_vars.includes(_key)) {
        _vars.push(_key)
        if (form.fieldlen && form.fieldlen > 2048) {
          form.fieldlen = 'max'
        }
        let _type = `nvarchar(${form.fieldlen})`
        if (form.type.match(/date/ig)) {
          _type = 'datetime'
        } else if (form.type === 'number') {
          _type = `decimal(18,${form.fieldlen})`
        }
        _declarefields.push(`@${_key} ${_type}`)
      }
    })
    if (data) {
      Object.keys(data).forEach(key => {
        data[key.toLowerCase()] = data[key]
      })
    }
    // 添加数据中字段,表单值优先(按钮不选行或多行拼接时跳过)
    if (data && btn.Ot !== 'notRequired' && btn.Ot !== 'requiredOnce') {
      datavars = {...data, ...datavars}
      const setField = (col) => {
        if (!col.field) return
        let _key = col.field.toLowerCase()
        if (!_initvars.includes(_key)) {
          let _val = datavars.hasOwnProperty(_key) ? datavars[_key] : ''
          _initvars.push(_key)
          _initColfields.push(`@${_key}='${_val}'`)
        }
      /*把自定义的友好的错误信息提示加上*/
      set @ErrorCode=cast(ERROR_NUMBER() as nvarchar(50))
      SET @retmsg=ERROR_MESSAGE();
      SELECT @ErrorMessage=ERROR_MESSAGE(),
        @ErrorSeverity=ERROR_SEVERITY(),
        @ErrorState=ERROR_STATE();
        
        if (!_vars.includes(_key)) {
          _vars.push(_key)
          if (col.datatype) {
            _declarefields.push(`@${_key} ${col.datatype}`)
          } else {
            if (col.fieldlength && col.fieldlength > 2048) {
              col.fieldlength = 'max'
            }
            let _type = `nvarchar(${col.fieldlength || 50})`
            if (col.type === 'number') {
              let _length = col.decimal ? col.decimal : 0
              _type = `decimal(18,${_length})`
            } else if (col.type === 'picture' || col.type === 'textarea') {
              _type = `nvarchar(${col.fieldlength || 512})`
            }
            _declarefields.push(`@${_key} ${_type}`)
          }
        }
      }
      if (columns && columns.length > 0) {
        columns.forEach(col => {
          if (col.type === 'colspan' || col.type === 'old_colspan') {
            col.subcols.forEach(cell => {
              setField(cell)
            })
          } else {
            setField(col)
          }
        })
      }
    }
    // 变量声明
    _declarefields = _declarefields.join(',')
    if (_declarefields) {
      _declarefields = ',' + _declarefields
    }
    _sql = `/* 系统生成 */
        Declare @tbid nvarchar(50),@ErrorCode nvarchar(50),@retmsg nvarchar(4000),@BillCode nvarchar(50),@BVoucher nvarchar(50),@FIBVoucherDate nvarchar(50), @FiYear nvarchar(50), @UserName nvarchar(50),@FullName nvarchar(50),@ModularDetailCode nvarchar(50)${_declarefields}
      `
    // 表单变量赋值
    if (_initFormfields.length > 0) {
      _sql += `
        /* 表单变量赋值 */
        select ${_initFormfields.join(',')}
        `
    }
    // 显示列变量赋值
    if (_initColfields.length > 0) {
      _sql += `
        /* 显示列变量赋值 */
        select ${_initColfields.join(',')}
        `
    }
    // 去除禁用的验证
    if (verify.contrasts) {
      verify.contrasts = verify.contrasts.filter(item => item.status !== 'false')
    }
    if (verify.uniques) {
      verify.uniques = verify.uniques.filter(item => item.status !== 'false')
    }
    if (verify.customverifys) {
      verify.customverifys = verify.customverifys.filter(item => item.status !== 'false')
    }
    if (verify.billcodes) {
      verify.billcodes = verify.billcodes.filter(item => item.status !== 'false')
    }
    let userName = sessionStorage.getItem('User_Name') || ''
    let fullName = sessionStorage.getItem('Full_Name') || ''
    if (sessionStorage.getItem('isEditState') === 'true') {
      userName = sessionStorage.getItem('CloudUserName') || ''
      fullName = sessionStorage.getItem('CloudFullName') || ''
    }
    // 初始化凭证及用户信息字段
    _sql += `
        /* 凭证及用户信息初始化赋值 */
        select @BVoucher='',@FIBVoucherDate='',@FiYear='',@ErrorCode='',@retmsg='',@UserName='${userName}', @FullName='${fullName}', @BillCode='', @ModularDetailCode=''
        `
    if (_initCustomScript) {
      _sql += _initCustomScript
    }
    // 启用账期验证
    if (verify.accountdate === 'true') {
      let orgcode = `''`
      let date = `''`
      if (verify.accountfield && _initvars.includes(verify.accountfield.toLowerCase())) {
        orgcode = '@' + verify.accountfield
      }
      if (verify.voucherdate && _initvars.includes(verify.voucherdate.toLowerCase())) {
        date = '@' + verify.voucherdate
      }
      _sql += `
        /* 账期验证 */
        exec s_FIBVoucherDateCheck @OrgCode=${orgcode},@FIBVoucherDate=${date},@ErrorCode=@ErrorCode OUTPUT,@retmsg=@retmsg OUTPUT
        if @ErrorCode!=''
          GOTO aaa
        `
    }
    // 失效验证,添加数据时不用
    if (btn.sqlType !== 'insert' && verify.invalid === 'true' && setting.dataresource) {
      let datasource = setting.dataresource
      if (/\s/.test(datasource) && !/tb$/.test(datasource)) { // 拼接别名
        datasource = '(' + datasource + ') tb'
      }
      if (setting.customScript) {
        _sql += `
        /* 数据源自定义脚本,请注意变量定义是否重复 */
        ${setting.customScript}
        `
      }
      if (btn.Ot === 'requiredOnce') {
        _sql += `
        /* 失效验证 */
        select @tbid='', @ErrorCode='',@retmsg=''
        select @tbid='X' from ${datasource} right join (select ID from  dbo.SplitComma(@ID@)) sp
        on tb.id =sp.id where tb.id is null
        If @tbid!=''
        Begin
          select @ErrorCode='E',@retmsg='数据已失效'
          goto aaa
        end
        `
      } else {
        _sql += `
        /* 失效验证 */
        select @tbid='', @ErrorCode='',@retmsg=''
        select @tbid=${primaryKey} from ${datasource} where ${primaryKey}=@ID@
        If @tbid=''
        Begin
          select @ErrorCode='E',@retmsg='数据已失效'
          goto aaa
        end
        `
      }
    }
    // 比较验证
    if (verify.contrasts && verify.contrasts.length > 0) {
      verify.contrasts.forEach(item => {
        _sql += `
        /* 比较验证 */
        If ${item.frontfield} ${item.operator} ${item.backfield}
        Begin
          select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
            goto aaa
        end
        `
      })
    }
      RAISERROR(@ErrorMessage, /*-- Message text.*/
        @ErrorSeverity, /*-- Severity.*/
        @ErrorState  /*-- State.*/
      );
    END CATCH
    
    // 自定义验证
    verify.customverifys && verify.customverifys.forEach(item => {
      _sql += `
        /* 自定义验证 */
        select @tbid='', @ErrorCode='',@retmsg=''
        select top 1 @tbid='X' from (${item.sql}) a
        If @tbid ${item.result === 'true' ? '!=' : '='}''
        Begin
          select @ErrorCode='${item.errorCode}',@retmsg='${item.errmsg}'
          goto aaa
        end
        `
    })
    // 单号生成,使用上级id(BID)或列表数据,声明变量(检验)
    let _billcodesSql  = ''
    if (formdata && verify.billcodes && verify.billcodes.length > 0) {
      let keys = formdata.map(item => item.key.toLowerCase()) // 表单字段
      verify.billcodes.forEach(item => {
        let _key = item.field.toLowerCase()
        let _linkKey = item.linkField ? item.linkField.toLowerCase() : ''
        if (!keys.includes(_key)) return // 表单中不含单号生成字段
        let _ModularDetailCode = ''
        let _lpline = ''
        if (item.TypeCharOne === 'Lp') {
          if (_linkKey === 'bid' && BID) { // 替换bid
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@BID@,48)`
          } else {
            _lpline = `set @ModularDetailCode= 'Lp'+ right('${item.mark || btn.uuid}'+@${_linkKey},48)`
          }
          _ModularDetailCode = '@ModularDetailCode'
        } else if (item.TypeCharOne === 'BN') {
          let _val = ''
          if (_linkKey === 'bid' && BID) { // 替换bid
            _val = BID
          } else if (data && data.hasOwnProperty(_linkKey)) {
            _val = data[_linkKey]
          }
          _ModularDetailCode = `'${item.TypeCharOne + _val}'`
        } else {
          _ModularDetailCode = `'${item.ModularDetailCode}'`
        }
        let _declare = ''
        if (!_vars.includes(_key)) {
          _declare = `Declare @${_key} nvarchar(50)`
          _vars.push(_key)
        }
        _billcodesSql += `
        /* 单号生成 */
        ${_declare}
        select @BillCode='', @${_key}='', @ModularDetailCode=''
        ${_lpline}
        exec s_get_BillCode
          @ModularDetailCode=${_ModularDetailCode},
          @Type=${item.Type},
          @TypeCharOne='${item.TypeCharOne}',
          @TypeCharTwo ='${item.TypeCharTwo}',
          @BillCode =@BillCode output,
          @ErrorCode =@ErrorCode output,
          @retmsg=@retmsg output
        if @ErrorCode!=''
          goto aaa
        set @${_key}=@BillCode
        `
      })
      if (_actionType !== 'insertOrUpdate') {
        _sql += _billcodesSql
      }
    }
    // 唯一性验证,必须存在表单(表单存在时,主键均为单值),必须填写数据源,多行拼接时不可用
    if (formdata && verify.uniques && verify.uniques.length > 0 && btn.Ot !== 'requiredOnce') {
      verify.uniques.forEach(item => {
        let _fieldValue = []                     // 表单键值对field=value
        let _value = []                          // 表单值,用于错误提示
        let _labels = item.fieldlabel.split(',') // 表单提示文字
        let arr = [] // 验证主键
        item.field.split(',').forEach((_field, index) => {
          let _key = _field.toLowerCase()
          let _val = datavars[_key] !== undefined ? datavars[_key] : ''
          let _fval = `'${_val}'`
          if (_key === 'bid' && !datavars.bid) { // 表单中没有bid则使用系统bid变量
            _fval = '@BID@'
          }
          if (_key === 'bid' && tab && tab.foreignKey) {
            arr.push(tab.foreignKey.toLowerCase())
            _fieldValue.push(`${tab.foreignKey}=${_fval}`)
          } else {
            arr.push(_key)
            _fieldValue.push(`${_key}=${_fval}`)
          }
          _value.push(`${_labels[index] || ''}:${_val || ''}`)
        })
        let _verifyType = ''
        if (item.verifyType === 'logic') {
          _verifyType = ' and deleted=0'
        }
        if (!arr.includes(primaryKey.toLowerCase())) {
          _fieldValue.push(`${primaryKey} !='${primaryId}'`)
        }
        _sql += `
        /* 唯一性验证 */
        select @tbid='', @ErrorCode='',@retmsg=''
        select @tbid='X' from ${btn.sql} where ${_fieldValue.join(' and ')}${_verifyType}
        If @tbid!=''
        Begin
          select @ErrorCode='${item.errorCode}',@retmsg='${_value.join(', ')} 已存在'
          goto aaa
        end
        `
      })
    } else if (verify.uniques && verify.uniques.length > 0 && btn.Ot === 'requiredOnce' && setting.dataresource) {
      let datasource = setting.dataresource
      if (/\s/.test(datasource)) { // 拼接别名
        if (!/tb$/.test(datasource)) {
          datasource = '(' + datasource + ') tb'
        }
      } else {
        datasource = datasource + ' tb'
      }
      if (setting.customScript) {
        _sql += `
        /* 数据源自定义脚本,请注意变量定义是否重复 */
        ${setting.customScript}
        `
      }
      verify.uniques.forEach(item => {
        _sql += `
        /* 同类数据验证 */
        Set @tbid=''
        Select top 1 @tbid='X' from (select distinct ${item.field},1 as n from ${datasource} inner join (select ID from  dbo.SplitComma(@ID@)) sp on tb.${primaryKey}=sp.ID ) a having sum(n)>1
        If @tbid!=''
        Begin
          Set @ErrorCode='E' Set @retmsg='${item.fieldlabel} 值不唯一'
          goto aaa
        end
        `
      })
    }
    let hasvoucher = false
    // 凭证-显示列中选取,必须选行
    if (verify.voucher && verify.voucher.enabled && data) {
      let _voucher = verify.voucher
      hasvoucher = true
      _sql += `
        /* 创建凭证 */
        exec s_BVoucher_Create
          @Bill ='${data[_voucher.linkField.toLowerCase()]}',
          @BVoucherType ='${_voucher.BVoucherType}',
          @VoucherTypeOne ='${_voucher.VoucherTypeOne}',
          @VoucherTypeTwo ='${_voucher.VoucherTypeTwo}',
          @Type =${_voucher.Type},
          @UserID=@UserID@,
          @Username=@Username,
          @FullName=@FullName,
          @BVoucher =@BVoucher OUTPUT ,
          @FIBVoucherDate =@FIBVoucherDate OUTPUT ,
          @FiYear =@FiYear OUTPUT ,
          @ErrorCode =@ErrorCode OUTPUT,
          @retmsg=@retmsg OUTPUT
        if @ErrorCode!=''
          GOTO aaa
        `
    }
    let _insertsql = ''
    if (_actionType === 'insert' || _actionType === 'insertOrUpdate') { // 添加语句
      let keys = []
      let values = []
      formdata.forEach(item => {
        if (item.writein === false) return
        let _key = item.key.toLowerCase()
        keys.push(_key)
        values.push('@' + _key)
      })
      if (!keys.includes(primaryKey.toLowerCase())) {
        keys.push(primaryKey.toLowerCase())
        values.push('\'' + primaryId + '\'')
      }
      if (!keys.includes('createuserid')) {
        keys.push('createuserid')
        values.push('@userid@')
      }
      if (!keys.includes('createuser')) {
        keys.push('createuser')
        values.push('@username')
      }
      if (!keys.includes('createstaff')) {
        keys.push('createstaff')
        values.push('@fullname')
      }
      if (!keys.includes('bid')) {
        if (tab && tab.foreignKey && !keys.includes(tab.foreignKey.toLowerCase())) {
          keys.push(tab.foreignKey.toLowerCase())
        } else {
          keys.push('bid')
        }
        values.push('@BID@')
      } else if (tab && tab.foreignKey && !keys.includes(tab.foreignKey.toLowerCase())) {
        keys.push(tab.foreignKey.toLowerCase())
        values.push('@BID@')
      }
      keys = keys.join(',')
      values = values.join(',')
      _insertsql = `insert into ${btn.sql} (${keys}) select ${values};`
    }
    let _updatesql = ''
    if (_actionType === 'update' || _actionType === 'audit' || _actionType === 'insertOrUpdate') { // 修改语句
      let _form = []
      let _arr = []
      formdata.forEach(item => {
        if (item.writein === false) return
        let _key = item.key.toLowerCase()
        _arr.push(_key)
        _form.push(_key + '=@' + _key)
      })
      if (_actionType === 'audit') {
        if (!_arr.includes('submitdate')) {
          _form.push('submitdate=getdate()')
        }
        if (!_arr.includes('submituserid')) {
          _form.push('submituserid=@userid@')
        }
      } else {
        if (!_arr.includes('modifydate')) {
          _form.push('modifydate=getdate()')
        }
        if (!_arr.includes('modifyuserid')) {
          _form.push('modifyuserid=@userid@')
        }
      }
    GOTO_RETURN:
      ROLLBACK TRAN
      
      if (hasvoucher) {
        if (!_arr.includes('bvoucher')) {
          _form.push('BVoucher=@BVoucher')
        }
        if (!_arr.includes('fibvoucherdate')) {
          _form.push('FIBVoucherDate=@FIBVoucherDate')
        }
        if (!_arr.includes('fiyear')) {
          _form.push('FiYear=@FiYear')
        }
      }
      _form = _form.join(',')
    END`
      let _ID = '=@ID@'
      if (btn.Ot === 'requiredOnce') {
        _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
      }
    Ltext = Ltext.replace(/\n\s{4}/ig, 'mchr13k')
      _updatesql = `update ${btn.sql} set ${_form} where ${primaryKey}${_ID};`
    }
    if (_prevCustomScript) {
      _sql += _prevCustomScript
    }
    // 添加、修改、逻辑删除、物理删除
    if (_actionType === 'insert') {
      _sql += `
        /* 默认sql */
        ${_insertsql}`
    } else if (_actionType === 'update' || _actionType === 'audit') {
      _sql += `
        /* 默认sql */
        ${_updatesql}`
    } else if (_actionType === 'LogicDelete') { // 逻辑删除
      let _ID = '=@ID@'
      if (btn.Ot === 'requiredOnce') {
        _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
      }
      _sql += `
        /* 默认sql */
        update ${btn.sql} set deleted=1,modifydate=getdate(),modifyuserid=@userid@ where ${primaryKey}${_ID};`
    } else if (_actionType === 'delete') {      // 物理删除
      let _msg = ''
      if (data && columns && columns.length > 0) {
        let _index = 0
        columns.forEach(col => {
          if (col.Hide !== 'true' && col.type !== 'colspan' && col.type !== 'old_colspan' && _index < 4) {
            _msg += col.label + '=' + data[col.field] + ','
            _index++
          }
        })
      }
      let _ID = '=@ID@'
      if (btn.Ot === 'requiredOnce') {
        _ID = ' in (select ID from  dbo.SplitComma(@ID@))'
      }
      _sql += `
        /* 默认sql */
        insert into snote (remark,createuserid,CreateUser,CreateStaff) select left('删除表:${btn.sql} 数据: ${_msg}${primaryKey}='+@ID@,200),@userid@,@username,@fullname
        delete ${btn.sql} where ${primaryKey}${_ID};`
    } else if (_actionType === 'insertOrUpdate') {
      _sql += `
        /* 默认sql */
        select @tbid=''
        select @tbid='X' from ${btn.sql} where ${primaryKey}=@ID@
        if @tbid=''
          begin
          ${_billcodesSql}
          ${_insertsql}
          end
        else
          begin
          ${_updatesql}
          end
      `
    }
    if (_backCustomScript) {
      _sql += _backCustomScript
    }
    if (retmsg) {
      _sql += `
          aaa: if @ErrorCode!=''
          insert into tmp_err_retmsg (ID, ErrorCode, retmsg, CreateUserID) select @time_id@,@ErrorCode, @retmsg,@UserID@`
    } else {
      _sql += `
          aaa: select @ErrorCode as ErrorCode,@retmsg as retmsg`
    }
    if ((window.GLOB.systemType !== 'production' && options.sysType !== 'cloud') || window.debugger === true) {
      _sql = _sql.replace(/\n\s{8}/ig, '\n')
      console.info(_sql)
    }
    return _sql
    return Ltext
  }
}