/* eslint-disable eqeqeq */
/* eslint-disable no-useless-escape */
/* eslint-disable dot-notation */
/* eslint-disable camelcase */
/* eslint-disable no-undef */
import { random, trim } from 'lodash'
import moment from 'moment'

const RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'

export function uuid (placeholder) {
  return RFC4122_TEMPLATE.replace(/[xy]/g, function () {
    let value = random(15)
    value = placeholder === 'x' ? value : (value & 0x3 | 0x8)
    return value.toString(16)
  })
}
/**
 * @return {string}
 */

export function setCookie (value, minutes = 30, path = '/') { // 设置cookie
  const expires = new Date(Date.now() + (minutes * 60000)).toGMTString()
  for (const item in value) {
    document.cookie = `${item}=${encodeURIComponent(value[item])};expires=${expires};path=${path}`
  }
}

export function getCookie (name) { // 获取cookie
  return document.cookie.split('; ').reduce((r, v) => {
    const parts = v.split('=')
    return parts[0] === name ? decodeURIComponent(parts[1]) : r
  }, '')
}

export function clearCookie (values, path = '/') { // 清除cookie
  setCookie(values, -1, path)
}

export function Base64_Encode (str) { // base64转换
  let c1, c2, c3
  const base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  let i = 0
  const len = str.length
  let string = ''

  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff
    if (i === len) {
      string += base64EncodeChars.charAt(c1 >> 2)
      string += base64EncodeChars.charAt((c1 & 0x3) << 4)
      string += '=='
      break
    }
    c2 = str.charCodeAt(i++)
    if (i === len) {
      string += base64EncodeChars.charAt(c1 >> 2)
      string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
      string += base64EncodeChars.charAt((c2 & 0xF) << 2)
      string += '='
      break
    }
    c3 = str.charCodeAt(i++)
    string += base64EncodeChars.charAt(c1 >> 2)
    string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
    string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6))
    string += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return string
}

export function guid () {
  function S4 () {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
  }
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()
}

export function extend (obj1, obj2) {
  if (typeof (obj2) === 'object') {
    for (const p in obj2) {
      obj1[p] = obj2[p]
    }
  }
}

// 查询条件
export function extendRule (obj, filed, op, value, isSysParam) {
  const data = {}
  if (value === null) {
    value = ''
  }
  data['Field'] = filed
  data['Operate'] = op
  data['Value'] = isSysParam ? value.toString() : value
  if (isSysParam) {
    data['IsSysParamRule'] = true
  }

  if (!obj.FilterGroup) {
    obj.FilterGroup = {}
  }
  if (!obj.FilterGroup.Rules) {
    obj.FilterGroup.Rules = []
  }
  obj.FilterGroup.Rules.push(data)
}

export function initFilterGroup (IsAnd = true) {
  return {
    IsAnd,
    Rules: [],
    Groups: []
  }
}

export function extendFilterGroup (obj, obj2) {
  if (!obj.FilterGroup) {
    obj.FilterGroup = {}
  }
  if (!obj.FilterGroup.Groups) {
    obj.FilterGroup.Groups = []
  }
  obj.FilterGroup.Groups.push(obj2)
}

export function extendChildGroup (obj, obj2) {
  if (!obj.Groups) {
    obj.Groups = []
  }
  obj.Groups.push(obj2)
}

// 查询条件
export function extendGroupRule (obj, filed, op, value, isSysParam) {
  const data = {}
  if (value === null) {
    value = ''
  }
  data['Field'] = filed
  data['Operate'] = op
  data['Value'] = isSysParam ? value.toString() : value
  if (isSysParam) {
    data['IsSysParamRule'] = true
  }

  if (!obj.Rules) {
    obj.Rules = []
  }
  obj.Rules.push(data)
}

export function initQueryFilter (OrgId, PageIndex, Limit, Sort, Order) {
  return {
    OrgId,
    PageIndex,
    Limit,
    Start: (PageIndex - 1) * Limit,
    Sort,
    Order: (Order === '' ? 0 : Order),
    RuleCount: 0,
    IncludeCount: 0,
    OrderCount: 0,
    FilterGroupCount: 0,
    Include: [],
    Orders: [],
    FilterGroup: { Rules: [], Groups: [] }
  }
}

export function initFilter (OrgId, Keyword = '', Sort, Order, PageIndex = 1, Parameter1, Parameter2, Parameter3, Parameter4, Parameter5, Parameter6) {
  return {
    Keyword,
    Parameter1,
    Parameter2,
    Parameter3,
    Parameter4,
    Parameter5,
    Parameter6,
    OrgId,
    PageIndex,
    Limit: 10,
    Start: (PageIndex - 1) * 10,
    Sort,
    Order: (Order === '' ? 0 : Order),
    RuleCount: 0,
    IncludeCount: 0,
    OrderCount: 0,
    FilterGroupCount: 0,
    Include: [],
    Orders: [],
    FilterGroup: { Rules: [], Groups: [] },
    SelectField: [],
    DataRule: []
  }
}

export function extendInclude (obj, clude) {
  if (!obj.Include) {
    obj.Include = []
  }
  obj.Include.push(clude)
}

export function extendOrder (obj, filed, order) {
  var data = {}
  data['Field'] = filed
  data['Order'] = order
  if (!obj.Orders) {
    obj.Orders = []
  }
  obj.Orders.push(data)
}

export function empty (v, allowZero) {
  if (v === 'null' || v === undefined || v === '') return true
  switch (typeof v) {
    case 'undefined':
      return true
    case 'string':
      return trim(v).length === 0
    case 'boolean':
      return !v
    case 'number':
      return v === 0 && !allowZero
    case 'object':
      if (v === null) return true
      if (v.length !== undefined && v.length === 0) return true
      return !!Object.keys(v).length
    default:
      return false
  }
}

// 点字符串转对象
export function strConvert (target, def) {
  // str为需要转换的值, def为有固定的最后一个属性值
  const splitFiles = target.split('.')
  let str = ''
  const len = splitFiles.length
  splitFiles.forEach(item => {
    str += '{\"' + item + '\":'
  })
  str += '' + def + ''
  for (let j = 0; j < len; j++) {
    str += '}'
  }
  const mat = JSON.parse(str)
  return mat
}

// 仅仅获取对象的基础属性，不包含属性中的对象
export function getOnlyPropertyData (data, isGetSysParam) {
  const result = {}
  Object.keys(data).forEach((n) => {
    if (n.indexOf('.') !== -1) return
    if (isGetSysParam && n === 'Nav_SysParams') {
      result[n] = data[n]
    } else if (typeof (data[n]) !== 'object') {
      result[n] = data[n]
    }
  })
  return result
}

// 仅仅获取对象的基础属性及列表，不包含属性中的对象
export function getPropertyData (data, isSetDelete) {
  const result = {}
  Object.keys(data).forEach((n) => {
    if (n.indexOf('.') != -1) return
    if (typeof (data[n]) !== 'object') {
      result[n] = data[n]
    } else if (data[n] && data[n].length) {
      const array = []
      data[n].forEach(nx => {
        const d = getPropertyData(nx, isSetDelete)
        array.push(d)
      })
      result[n] = array
    }
    if (isSetDelete) {
      result['IS_DELETED'] = true
    }
  })
  return result
}

// 取导航属性的最后一个字段
export function dataIndexName (field) {
  const valueValid = field ? field.split('.') : []
  return valueValid[valueValid.length - 1]
}

export function splitEnum (str) {
  const newArr = []
  const oArr = str ? str.split(',') : []
  oArr.forEach(item => {
    const n = item.split(':')
    newArr.push({
      label: n[0],
      value: n[1]
    })
  })
  return newArr
}

export function getDataFieldValueByCol (data, field, defaultValue) {
  if (!data || !field) return null
  let opIndex = field.lastIndexOf('/')
  let op = 0
  if (opIndex === -1) {
    opIndex = field.indexOf('*')
    if (opIndex === -1) {
      opIndex = field.indexOf('+')
      if (opIndex === -1) {
        opIndex = field.lastIndexOf('-')
        if (opIndex !== -1) {
          op = 2
        }
      } else {
        op = 1
      }
    } else {
      op = 3
    }
  } else {
    op = 4
  }

  let controlValue = null
  if (opIndex !== -1) {
    const leftField = field.substring(0, opIndex)
    const rightField = field.substring(opIndex + 1)
    const leftText = getDataFieldValueByCol(data, leftField)
    const rigthText = getDataFieldValueByCol(data, rightField)
    if (leftText !== '' && rigthText !== '' && !isNaN(leftText) && !isNaN(rigthText)) {
      if (op === 1) {
        controlValue = (+leftText) + (+rigthText)
      } else if (op === 2) {
        controlValue = (+leftText) - (+rigthText)
      } else if (op === 3) {
        controlValue = (+leftText) * (+rigthText)
      } else if (op === 3 && (+rigthText) !== 0) {
        controlValue = (+leftText) / (+rigthText)
      }
    }
  } else {
    controlValue = getDataFieldValue(data, field, defaultValue)
  }
  return controlValue
}

function innerGetDataFieldValue (data, field, defaultValue) {
  if (!data || !field) return null
  const valueValid = field ? field.split('.') : []
  let controlValue = null
  let tmp = { ...data }
  if (tmp) {
    for (let j = 0; j < valueValid.length; j++) {
      if (j < valueValid.length - 1) {
        if (tmp && Object.prototype.hasOwnProperty.call(tmp, valueValid[j])) {
          tmp = tmp[valueValid[j]]
        } else {
          tmp = null
        }
      } else {
        if (tmp && Object.prototype.hasOwnProperty.call(tmp, valueValid[j])) {
          controlValue = tmp[valueValid[j]]
        }
      }
    }
  }
  if (controlValue == null && defaultValue !== undefined) {
    return defaultValue
  }
  return controlValue
}

export function getDataFieldValue (data, field, defaultValue) {
  if (!data || !field) {
    if (defaultValue !== undefined) {
      return defaultValue
    }
    return null
  }
  const key = 'Nav_SysParams'
  const index = field.indexOf(key)
  if (index === -1) {
    return innerGetDataFieldValue(data, field, defaultValue)
  } else {
    const f1 = index > 0 ? field.substring(0, index - 1) : null
    const f2 = field.substring(index + key.length + 1)
    let temp = null
    if (f1) {
      temp = innerGetDataFieldValue(data, f1)
    } else {
      temp = data
    }
    if (temp) {
      const sysParams = temp[key]
      if (sysParams) {
        const paramRecord = sysParams.filter(t => t.CODE === f2)[0]
        if (paramRecord) {
          return paramRecord.VALUE
        }
      }
    }
  }
  if (defaultValue !== undefined) {
    return defaultValue
  }
  return null
}

function innerSetDataFieldValue (data, field, value) {
  let tmp = data
  const valueValid = field ? field.split('.') : []
  for (let j = 0; j < valueValid.length; j++) {
    if (j < valueValid.length - 1) {
      if (!Object.prototype.hasOwnProperty.call(tmp, valueValid[j]) || !tmp[valueValid[j]]) {
        tmp[valueValid[j]] = {}
      }
      let tmpData = tmp[valueValid[j]]
      if (!tmpData) {
        tmpData = {}
      }
      tmp = tmpData
    } else {
      tmp[valueValid[j]] = value
    }
  }
  return data
}
export function setDataFieldValue (data, field, value) {
  if (!data || !field) return data
  const key = 'Nav_SysParams'
  const index = field.indexOf(key)
  if (index === -1) {
    innerSetDataFieldValue(data, field, value)
  } else {
    const f1 = index > 0 ? field.substring(0, index - 1) : null
    const f2 = field.substring(index + key.length + 1)
    let temp = null
    if (f1) {
      temp = innerGetDataFieldValue(data, f1)
      if (!temp) {
        temp = {}
        innerSetDataFieldValue(data, f1, temp)
      }
    } else {
      temp = data
    }
    let sysParams = temp[key]
    if (!sysParams) {
      sysParams = []
      temp[key] = sysParams
    }
    let paramRecord = sysParams.filter(t => t.CODE === f2)[0]
    if (!paramRecord) {
      paramRecord = {
        ID: guid(),
        CODE: f2,
        ENTITY_ID: temp.ID
      }
      sysParams.push(paramRecord)
    }
    paramRecord.VALUE = value
  }
  return data
}

export function getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc, thisRef) {
  if (value && typeof (value) == 'string') {
    let index = value.indexOf("@user.");
    let departmentIndex = value.indexOf("@department.");
    let teamIndex = value.indexOf("@team.");
    if (index == 0) {
      let field = value.substring(6);
      if (field) {
        if (user) {
          value = getDataFieldValue(user, field, null);
        }
      };
    } else if (departmentIndex == 0) {
      let field1 = value.substring(12);
      if (field1) {
        if (user && user.Nav_Department) {
          value = getDataFieldValue(user.Nav_Department, field1, null);
        } else {
          value = "";
        }
      };
    } else if (teamIndex == 0) {
      let field2 = value.substring(6);
      if (field2) {
        if (user && user.Team) {
          value = getDataFieldValue(user.Team, field2, null);
        } else {
          value = '00000000-0000-0000-0000-000000000000';
        }
      };
    }
    else {
      index = value.indexOf("@nowDate");
      if (index == 0) {
        value = moment().format('YYYY-MM-DD');
      } else {
        index = value.indexOf("@nowTime");
        if (index == 0) {
          value = moment().format('HH:mm:ss');
        } else {
          index = value.indexOf("@now");
          if (index == 0) {
            value = moment().format('YYYY-MM-DD HH:mm:ss');
          } else {
            index = value.indexOf("@head.");
            if (index == 0) {
              const field = value.substring(6);
              if (field && typeof getHeadFieldValueFunc === 'function') {
                value = getHeadFieldValueFunc(field, thisRef);
              };
            } else {
              index = value.indexOf("@record.");
              if (index === 0) {
                const field = value.substring(8);
                if (field && typeof getRecordFieldValueFunc === 'function') {
                  value = getRecordFieldValueFunc(field, thisRef);
                };
              }
            }
          }
        }
      }


    }
  }
  return value;
}

export function permissionUtils (login) {
  const checkPermission = (formId, keyId, type) => {
    if (login.userType == 99 || !formId) return true // 管理员
    let hasPermission = false
    const currActivatedMenu = login.currActivatedMenu || {}
    if (login.rolePerm && login.rolePerm.Nav_RolePermForms && login.rolePerm.Nav_RolePermForms.length) { // 只要一个角色有权限就有权限
      login.rolePerm.Nav_RolePermForms.forEach((n1, i1) => {
        if (n1.PermFormId === formId) {
          const matchForm = n1.MenuId === currActivatedMenu.ID
          if (type == 0 && matchForm) { // 表单权限
            hasPermission = true
          } else if (type == 1) { // 按钮权限
            if (n1.Nav_Btns && n1.Nav_Btns.length) {
              n1.Nav_Btns.forEach((n2, i2) => {
                const matchBtn = n2.MenuId === currActivatedMenu.ID
                if (n2.BtnId === keyId && matchBtn) {
                  hasPermission = true
                }
              })
            }
          } else if (type == 2) { // 行权限
            if (n1.Nav_Columns && n1.Nav_Columns.length) {
              n1.Nav_Columns.forEach((n2, i2) => {
                const matchRow = n2.MenuId === currActivatedMenu.ID
                if (n2.ColumnId === keyId && matchRow) {
                  hasPermission = true
                }
              })
            }
          }
        }
      })
    }
    return hasPermission
  }
  return {
    checkBtn: (formId, btnId) => {
      return checkPermission(formId, btnId, 1)
    },
    checkColumn: (formId, columnId) => {
      return checkPermission(formId, columnId, 2)
    },
    checkForm: (formId) => {
      return checkPermission(formId, '', 0)
    }
  }
}

// 根据枚举字符串获取枚举列表
export function getEnums (str) {
  const newArr = {}
  const oArr = str ? str.split(',') : []
  oArr.forEach(item => {
    const n = item.split(':')
    newArr[[n[1]]] = n[0]
  })
  return newArr
}

export function getCustomParams (customParamsStr) {
  const customParams = {}
  if (customParamsStr) {
    const arrays = customParamsStr.split('|')
    arrays.forEach(function (n, i) {
      const paris = n.split('=')
      if (paris.length >= 2) {
        customParams[paris[0]] = paris[1]
      } else {
        customParams[paris[0]] = null
      }
    })
  }
  return customParams
}

export function getParseValueByDate (date) {
  if (date) {
    let r = null
    if (date === '{now}') {
      r = [moment(), moment()]
    } else if (date.indexOf('{now,') > -1) {
      const tt1 = date.indexOf('}')
      const et = tt1 > -1 ? date.substring(tt1 + 1) : null
      if (et && et.indexOf('{now,') > -1) {
        const bs = date.substring(0, tt1 + 1)
        let b1 = bs.substring(5)
        let e1 = et.substring(5)
        b1 = b1.substring(0, b1.length - 1)
        e1 = e1.substring(0, e1.length - 1)
        const bts = b1.split(',')
        const ets = e1.split(',')
        if (bts && bts.length >= 2 && ets && ets.length >= 2) {
          const n1 = bts[1]
          const n2 = ets[1]
          const b = n1 > 0 ? moment().add(n1, bts[0]) : (n1 < 0 ? moment().subtract(Math.abs(n1), bts[0]) : moment())
          const e = n2 > 0 ? moment().add(n2, ets[0]) : (n2 < 0 ? moment().subtract(Math.abs(n2), ets[0]) : moment())
          if (b.isBefore(e)) {
            r = [b, e]
          }
        }
      } else {
        let t = date.substring(5)
        t = t.substring(0, t.length - 1)
        const ts = t.split(',')
        if (ts && ts.length >= 2) {
          if (ts.length === 2) {
            const n1 = ts[1]
            if (n1 > 0) {
              r = [moment(), moment().add(n1, ts[0])]
            } else if (n1 < 0) {
              r = [moment().subtract(Math.abs(n1), ts[0]), moment()]
            } else {
              r = [moment(), moment()]
            }
          } else {
            const n1 = ts[1]
            const n2 = ts[2]
            const b = n1 > 0 ? moment().add(n1, ts[0]) : (n1 < 0 ? moment().subtract(Math.abs(n1), ts[0]) : moment())
            const e = n2 > 0 ? moment().add(n2, ts[0]) : (n2 < 0 ? moment().subtract(Math.abs(n2), ts[0]) : moment())
            if (b.isBefore(e)) {
              r = [b, e]
            }
          }
        } else if (ts.length == 1 && ts[0].indexOf(',') == -1 && ts[0].indexOf('-') > -1) {
          r = [moment().format(ts[0]), moment()] //wyw 获取当前时间的格式时间(BS070 搜索效率低 加限制)
        }
      }
    } else {
      const temps = date ? date.split(',') : null
      if (temps && temps.length === 2) {
        r = [moment(temps[0]), moment(temps[1])]
      }
    }
    return r
  }
  return null
}

export function getGroupByQueryFields (fields, groups, parentId, parent, list) {
  if (groups && groups.length) {
    const tempGroups = groups.filter(t => t.PARENT_ID === parentId)
    if (tempGroups && tempGroups.length) {
      tempGroups.forEach(t => {
        const group = {
          rules: [],
          childGroups: [],
          isAnd: t.RELATION_TYPE !== 1
        }
        if (fields && fields.length) {
          const tempFields = fields.filter(t1 => t1.USER_C_C_QUERY_GROUP_ID === t.ID)
          if (tempFields && tempFields.length) {
            group.rules = getRulesByQueryFields(tempFields, group.childGroups)
          }
        }
        if (parent) {
          parent.childGroups.push(group)
        } else {
          list.push(group)
        }
        getGroupByQueryFields(fields, groups, t.ID, group, list)
      })
    }
  }
}

export function getRuleAndGroupsByQueryFields (queryFields, queryGroups) {
  const result = {}
  if (queryFields != null && queryFields.length) {
    const sysFields = queryFields.filter(t => !t.USER_C_C_QUERY_GROUP_ID)
    result.groups = []
    result.rules = getRulesByQueryFields(sysFields, result.groups)
    getGroupByQueryFields(queryFields, queryGroups, null, null, result.groups)
  }
  return result
}

export function getRulesByQueryFields (queryFields, groupList) {
  if (queryFields && queryFields.length) {
    const result = []
    queryFields.forEach(t => {
      if (t.DATA_VALUE === null || t.DATA_VALUE === undefined || t.DATA_VALUE === '') return
      // dataType-controlType
      // 5-10: 时分秒区间组件 9-18：月份 10-19：月份区间 12-20：年份 13-20：年份区间 15-22：年月日时分秒区间 16-23：年月日时分区间 17-2：日期选择
      if (
        t.DATA_TYPE === 5 ||
        t.DATA_TYPE === 9 ||
        t.DATA_TYPE === 10 ||
        t.DATA_TYPE === 12 ||
        t.DATA_TYPE === 13 ||
        t.DATA_TYPE === 15 ||
        t.DATA_TYPE === 16 ||
        t.DATA_TYPE === 17
      ) {
        const tmps = getParseValueByDate(t.DATA_VALUE)
        if (tmps != null && tmps.length) {
          if (t.IS_CUSTOM) {
            const vas = tmps.map((time, timeIndex) => {
              return timeIndex === 0 ? moment(time).format('YYYY-MM-DD') : moment(moment(time).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
            })
            // 将 2020-07-18 格式化成 2020-07-01 月份开始的时间
            const monthFormat = moment(moment(vas[0]).format('YYYY-MM')).format('YYYY-MM-DD')
            const monthEndFormat = moment(moment(vas[1]).format('YYYY-MM')).format('YYYY-MM-DD')
            // 将 2020-07-18 格式化成 2020-01-01 月份开始的时间
            const yearFormat = moment(moment(vas[0]).format('YYYY')).format('YYYY-MM-DD')
            const yearEndFormat = moment(moment(vas[1]).format('YYYY')).format('YYYY-MM-DD')
            // 年月日时分或者秒控件
            const dateHMOrS = tmps.map(item => {
              if (t.DATA_TYPE === 15) {
                // 年月日时分秒控件
                return moment(item).format('YYYY-MM-DD HH:mm:ss')
              }
              // 将 2020-07-18 18:24:15 格式化成 2020-07-18 18:24:00 开始的时间
              return moment(moment(item).format('YYYY-MM-DD HH:mm')).format('YYYY-MM-DD HH:mm:ss')
            })
            let dateVal = vas.join(',')
            switch (t.DATA_TYPE) {
              case 9:
                dateVal = monthFormat
                break
              case 10:
                dateVal = [monthFormat, monthEndFormat].join(',')
                break
              case 12:
                dateVal = yearFormat
                break
              case 13:
                dateVal = [yearFormat, yearEndFormat].join(',')
                break
              case 15:
              case 16:
                dateVal = dateHMOrS.join(',')
                break
              case 17:
                dateVal = vas[0]
                break
              default:
                break
            }
            result.push({
              field: t.QUERY_NAME,
              operator: 0,
              value: dateVal,
              isCustom: t.IS_CUSTOM,
              isSysParam: t.IS_SYS_PARAM
            })
          } else {
            let tempList = result
            const group = {
              isAnd: true,
              rules: []
            }
            if (groupList) {
              groupList.push(group)
              tempList = group.rules
            }
            tmps.forEach((j, k) => {
              const tmpVal = k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
              const monthVal = moment(moment(j).format('YYYY-MM')).format('YYYY-MM-DD')
              const yearVal = moment(moment(j).format('YYYY')).format('YYYY-MM-DD')
              const dateHMS = moment(j).format('YYYY-MM-DD HH:mm:ss') // 15 精确到年月日时分秒
              const dateHM = moment(j).format('YYYY-MM-DD HH:mm') // 16 精确到年月日时分
              tempList.push({
                field: t.QUERY_NAME,
                operator: k === 0 ? '6' : '4',
                value: t.DATA_TYPE === 5 || t.DATA_TYPE === 17 ? (t.DATA_TYPE === 16 ? dateHM : t.DATA_TYPE === 15 ? dateHMS : tmpVal) : (t.DATA_TYPE === 9 || t.DATA_TYPE === 10 ? monthVal : yearVal),
                isCustom: t.IS_CUSTOM,
                isSysParam: t.IS_SYS_PARAM
              })
            })
          }
        }
      } else if (t.DATA_TYPE === 3 || t.DATA_TYPE === 2) { // 枚举 数值
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '1',
          value: (+t.DATA_VALUE),
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM
        })
      } else if (t.DATA_TYPE === 4) { // 布尔
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '1',
          value: t.DATA_VALUE && t.DATA_VALUE == 'true',
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM
        })
      } else if (t.DATA_TYPE === 6) { // 下拉多选
        let temps = []
        if (t.DATA_VALUE.toString().indexOf(',') > -1) {
          temps = t.DATA_VALUE.toString().split(',')
        } else if (t.DATA_VALUE.toString().indexOf('_') > -1) {
          const tmp = t.DATA_VALUE.toString().split('_')
          tmp.forEach((n, i) => {
            if (n !== '') temps.push(n)
          })
        }

        let tempList = result
        const group = {
          isAnd: false,
          rules: []
        }
        if (groupList) {
          groupList.push(group)
          tempList = group.rules
        }
        temps.forEach((j, k) => {
          tempList.push({
            field: t.QUERY_NAME,
            operator: '1',
            value: j,
            isCustom: t.IS_CUSTOM,
            isSysParam: t.IS_SYS_PARAM
          })
        })
      } else {
        result.push({
          field: t.QUERY_NAME,
          operator: t.OP_DEFAULT ? t.OP_DEFAULT : '1',
          //value: t.DATA_VALUE,
          isCustom: t.IS_CUSTOM,
          isSysParam: t.IS_SYS_PARAM
        })
      }
    })
    return result
  }
}

export function locationQuery (query) {
  if (!query) return {}
  const querys = query.split('?')[1]
  const pair = querys.split('&')
  const obj = {}
  for (let i = 0; i < pair.length; i++) {
    const propertys = pair[i].split('=')
    obj[propertys[0]] = propertys[1]
  }
  return obj
}

export function getRuleAndGroupByParseValue ({
  ruleJson,
  field,
  operator,
  value,
  user,
  isCustom,
  getHeadFieldValueFunc,
  getRecordFieldValueFunc
}) {
  if (isCustom) { // 自定义字段
    if (value.indexOf('{now') > -1) {
      const temps = getParseValueByDate(value)
      let vas = ''
      temps.forEach((j, k) => {
        const v = k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
        vas += v + ','
      })
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: vas,
          isCustom: isCustom
        })
      }
    } else {
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc),
          isCustom: isCustom
        })
      }
    }
  } else {
    if (value.indexOf('{now') > -1) {
      if (ruleJson) {
        const groups = ruleJson.groups ? ruleJson.groups : ruleJson.childGroups
        if (groups) {
          const group = {
            isAnd: true,
            rules: []
          }
          groups.push(group)
          const temps = getParseValueByDate(value)
          temps.forEach((j, k) => {
            group.rules.push({
              field,
              operator: (k === 0 ? '6' : '4'),
              value: (k === 0 ? moment(j).format('YYYY-MM-DD') : moment(moment(j).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')),
              isCustom: isCustom
            })
          })
        }
      }
    } else {
      if (ruleJson && ruleJson.rules) {
        ruleJson.rules.push({
          field,
          operator,
          value: getParseValue(value, user, getHeadFieldValueFunc, getRecordFieldValueFunc),
          isCustom: isCustom
        })
      }
    }
  }
}

export function addChildGroups (list, group) {
  if (list && list.length) {
    list.forEach(t => {
      const tempGroup = initFilterGroup(t.isAnd)
      if (t.rules && t.rules.length) {
        t.rules.forEach(t1 => {
          extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam)
        })
      }
      if (t.childGroups && t.childGroups.length) {
        addChildGroups(t.childGroups, tempGroup)
      }
      extendChildGroup(group, tempGroup)
    })
  }
}

export function getRandomCode (len) {
  len = len || 32
  /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678=-*&@#$%!~+,./?\;:|'
  var maxPos = $chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

export function addRuleAndGroups (json, ruleAndGroupJson) {
  if (json && ruleAndGroupJson) {
    if (ruleAndGroupJson.rules && ruleAndGroupJson.rules.length) {
      ruleAndGroupJson.rules.forEach(t => {
        if (t.isCustom) { // 自定义字段
          if (t.field.indexOf(',') > -1) { // modify by陈昌雨 2020/6/4
            var splitFileds = t.field.split(',')
            let values = null
            if (typeof (t.value) === 'number' && t.value !== undefined && t.value != null) {
              values = t.value.toString().split(',')
            } else {
              values = t.value.split(',')
            }

            if (splitFileds && values) {
              splitFileds.forEach((n, i) => {
                json[n] = values[i]
              })
            }
          } else {
            json[t.field] = t.value
          }
        } else {
          extendRule(json, t.field, t.operator, t.value, t.isSysParam)
        }
      })
    }

    if (ruleAndGroupJson.groups && ruleAndGroupJson.groups.length) {
      ruleAndGroupJson.groups.forEach(t => {
        const tempGroup = initFilterGroup(t.isAnd)
        if (t.rules && t.rules.length) {
          t.rules.forEach(t1 => {
            extendGroupRule(tempGroup, t1.field, t1.operator, t1.value, t1.isSysParam)
          })
        }
        if (t.childGroups && t.childGroups.length) {
          addChildGroups(t.childGroups, tempGroup)
        }
        extendFilterGroup(json, tempGroup)
      })
    }
    if (ruleAndGroupJson.orgType) {
      json.OrgType = ruleAndGroupJson.orgType
    }
    if (ruleAndGroupJson.menuParameter) {
      json.MenuParameter = ruleAndGroupJson.menuParameter
    }
  }
}

export function constructStandardTreeData (data, cascader) {
  data.forEach(item => {
    const { Node, Children } = item
    const { NAME, ID } = Node
    if (cascader) {
      item.label = NAME
      item.value = ID
      Array.isArray(Children) && Children.length && (item.children = Children)
      for (const key in Node) {
        item[key] = Node[key]
      }
    } else {
      item.title = NAME
      item.key = ID
      item.value = ID
      item.children = Children
    }
    if (Array.isArray(Children) && Children.length) {
      constructStandardTreeData(Children, cascader)
    }
  })
}

function matchVal (target, source, result) {
  for (let i = 0, j = source.length; i < j; i++) {
    const { title, label, value, children } = source[i]
    if (value === target) {
      result.push(title || label)
    }
    if (Array.isArray(children) && children.length) matchVal(target, children, result)
  }
}

export function renderExportCell (text, record = [], config, enums) {
  if (config) {
    const { enumName } = config
    if (enumName) {
      return enums[enumName] && enums[enumName].enums ? (enums[enumName].enums[text] || text) : text
    }
    if (config.isBool || config.controlType === 101) {
      text = text ? '是' : '否'
    } else if (config.isDate || config.controlType === 102) { // 日期
      text = text.toString().substring(0, 10)
    } else if (config.controlType === 2) { // 显示日期根据控件类型格式化
      moment(text).isValid() && (text = moment(text).format('YYYY-MM-DD'))
    } else if (config.controlType === 8) {
      moment(text).isValid() && (text = moment(text).format('HH:mm:ss'))
    } else if (config.controlType === 10) {
      const dates = (text || '').split(',')
      if (moment(dates[0]).isValid() && moment(dates[1]).isValid()) {
        text = [moment(dates[0]).format('YYYY-MM-DD'), moment(dates[1]).format('YYYY-MM-DD')].join(',')
      }
    } else if (config.controlType === 18) {
      moment(text).isValid() && (text = moment(text).format('YYYY-MM'))
    } else if (config.controlType === 19) {
      const months = (text || '').split(',')
      if (moment(months[0]).isValid() && moment(months[1]).isValid()) {
        text = [moment(months[0]).format('YYYY-MM'), moment(months[1]).format('YYYY-MM')].join(',')
      }
    } else if (config.controlType === 9) { // 分页下拉
      if (Array.isArray(record) && record.length) {
        const values = (text || '').split(',')
        const texts = []
        values.forEach(item => {
          const findNode = record.find(rec => rec.ID === item)
          findNode && texts.push(`${findNode.CODE}-${findNode.NAME}`)
        })
        if (texts.length) return texts.join(',')
      }
    } else if (config.controlType === 11 || config.controlType === 17) { // 下拉树选择、级联选择
      if (Array.isArray(record) && record.length) {
        const valueArr = (text || '').split(',')
        // 级联选择，取最叶子节点
        const values = config.controlType === 17 ? [valueArr[valueArr.length - 1]] : valueArr
        const texts = []
        values.forEach(item => matchVal(item, record, texts))
        if (texts.length) return texts.join(',')
      }
    }
  }
  return text
}
