import _ from 'lodash'
const emptyList = [undefined, null]
// 解析url的问号参数
function parseUrlQueryString() {
  const host = decodeURIComponent(location.hash)
  const queryObj = {}
  if (host.includes('?')) {
    const query = host.split('?')[1]
    const queryList = query.split('&')
    queryList.forEach(item => {
      const iObj = item.split('=')
      queryObj[iObj[0]] = iObj[1]
    })
  }
  return queryObj
}
// 获取登录信息
function parseGlobalParams() {
  const globalParam = {}
  let user_info = sessionStorage['user_info']
  if (user_info && user_info !== 'undefined') {
    user_info = JSON.parse(user_info)
  }
  Object.assign(globalParam, user_info)
  return globalParam
}
// 解析queryBi dync页面路由上的appCode 和pageName
function parseUrlQueryBIDyncAppcodePageName() {
  const hash = decodeURIComponent(location.hash)
  const hostSplit = hash.split('?')
  let target = hostSplit[0]
  // 如果说最后一位是‘/’ 则删除掉
  if (target.endsWith('/')) {
    target = target.substr(0, target.length - 1)
  }
  const targetSplit = target.split('/')
  const length = targetSplit.length
  let pagename = targetSplit[length - 1]
  const appCode = targetSplit[length - 2]
  if (pagename.includes('/')) {
    pagename = pagename.split('/')[0]
  }
  if (pagename.includes('?')) {
    pagename = pagename.split('?')[0]
  }
  return {
    appCode: appCode,
    pagename: pagename
  }
}
// 解析动态菜单参数和全局参数MenuParams GlobalParams
function parseMenuGlobalParams(str, params) {
  const { menuParam, globalParam, currentRowParam, mainParam, searchParam, indexParam, currentParam } = params
  const empyt = [undefined]
  if (typeof str !== 'string' || !str.includes('{') || !str.includes('}')) return str
  const reg = /\{(.*?)\}/g //  /(?<=\{).*?(?=\})/g
  const strList = str.match(reg) || []// value_.match(/(?<=\{).*?(?=\})/g) || [] // value_.match(reg) || [] //
  strList.forEach(p => {
    const p_ = p.replace('{', '').replace('}', '')
    const props = p_.split('.')
    const sourceStr = props[0]
    const propStr = props[1]
    let pt = ''
    if (sourceStr === 'menuParam') {
      if (empyt.includes(menuParam[propStr])) {
        pt = p
      } else {
        pt = menuParam[propStr]
      }
    } else if (sourceStr === 'globalParam') {
      if (empyt.includes(globalParam[propStr])) {
        pt = p
      } else {
        pt = globalParam[propStr]
      }
    } else if (sourceStr === 'mainParam') {
      if (empyt.includes(mainParam[propStr])) {
        pt = p
      } else {
        pt = mainParam[propStr]
      }
    } else if (sourceStr === 'searchParam') {
      if (empyt.includes(searchParam[propStr])) {
        pt = p
      } else {
        pt = searchParam[propStr]
      }
    } else if (sourceStr === 'indexParam') {
      if (empyt.includes(indexParam[propStr])) {
        pt = p
      } else {
        pt = indexParam[propStr]
      }
    } else if (sourceStr === 'currentParam') {
      if (empyt.includes(currentParam[propStr])) {
        pt = p
      } else {
        pt = currentParam[propStr]
      }
    } else if (sourceStr === 'currentRowParam') {
      if (empyt.includes(currentParam[propStr])) {
        pt = p
      } else {
        pt = currentRowParam[propStr]
      }
    }
    pt = decodeURIComponent(pt)
    if (pt === 'false' || pt === 'true') {
      str = pt !== 'false'// str.replace(`{${p_}}`, pt)
    } else {
      str = str.replace(`{${p_}}`, pt)
    }
  })
  return str
}
// 递归替换动态参数
function recursiveDyncParam(obj, otherOBj = {}) {
  const parseUrlQueryParams = parseUrlQueryString() || {}
  const parseGlobalParams_ = parseGlobalParams() || {}
  const parms = {
    menuParam: parseUrlQueryParams, globalParam: parseGlobalParams_
  }
  Object.assign(parms, otherOBj)
  const objType = typeof obj
  if (Array.isArray(obj)) {
    obj.forEach((item, index) => {
      if (typeof item === 'object') {
        this.recursiveDyncParam(item, otherOBj)
      } else {
        obj[index] = parseMenuGlobalParams(item, parms)
      }
    })
  } else if (objType === 'object') {
    for (const prop in obj) {
      if (typeof obj[prop] === 'object') {
        this.recursiveDyncParam(obj[prop], otherOBj)
      } else {
        obj[prop] = parseMenuGlobalParams(obj[prop], parms)
      }
    }
  } else {
    return parseMenuGlobalParams(obj, parms)
  }
}
function filterSingleRow(newObj, oldObj, prop = 'id') {
  delete newObj.isSelected
  delete oldObj.isSelected
  const _newObj = _.cloneDeep(newObj)
  const _oldObj = _.cloneDeep(oldObj)
  const result = {}
  for (const p in _newObj) {
    if ((_oldObj[p] !== _newObj[p] && !emptyList.includes(_newObj[p])) || p === prop) {
      result[p] = _newObj[p]
    }
  }
  return result
}
// newData:当前数据.oldData:原始数据,primaryKey;主键id,reservedObj:保留字段
function comparisonArray(newData_, oldData_, primaryKey, reservedArray = []) {
  const newData = _.cloneDeep(newData_)
  const oldData = _.cloneDeep(oldData_)
  const emptyValue = [undefined, 'undefined', '']
  // 1,找出原始数据中所有的id
  const old_ids = oldData.reduce((pre, curr) => {
    const id = curr[primaryKey]
    if (id) {
      pre.push(id)
    }
    return pre
  }, [])
  // 2,找出新数据中所有项的id
  const new_ids = newData.reduce((pre, curr) => {
    const id = curr[primaryKey]
    if (id) {
      pre.push(id)
    }
    return pre
  }, [])

  // 3,找出删除项
  const delete_ids = old_ids.filter(item => {
    if (!new_ids.includes(item)) {
      return item
    }
  })
  const newItems = newData_.filter(item => {
    if (item.iUpdateStatus === 1) {
      return item
    }
  })

  // 找出修改项目
  const edit_item = newData.filter(item => {
    delete item.isSelected
    const id = item[primaryKey]
    const curr_old_item = oldData.find(element => {
      if (element[primaryKey] === id && item.iUpdateStatus !== 1) {
        return element
      }
    })
    if (id && curr_old_item) {
      // 找出变化的字段 并且保留必要字段
      for (const key in curr_old_item) {
        const hasKey = key in item
        if (!hasKey) { // 如果这个字段不在现有行中 则视为删除了
          item[key] = ''
        } else { // 如果字段对应的值相等 则视为 没更改 提交数据时把这个这段排除
          if (curr_old_item[key] === item[key] && key !== primaryKey && !reservedArray.includes(key)) {
            delete item[key]
          }
        }
      }
      const length1 = Object.keys(item).length
      if (length1 > 1) {
        return item
      }
    }
  })
  // 组装数据
  // 为新增项加一个标示
  newItems.forEach((item, index) => {
    delete item.isSelected
    // 删除空值
    for (const key in item) {
      const value = item[key]
      if (emptyValue.includes(value)) {
        delete item[key]
      }
    }
    delete item._columns
  })
  // 筛选出非空项
  const newItems_ = newItems.filter(item => Object.keys(item).length)
  // 为修改项加标示
  edit_item.filter(item => Object.keys(item).length).forEach(item => {
    delete item.isSelected
    for (const k in item) {
      if (item[k] === undefined) {
        item.k = ''
      }
    }
    if (Object.keys(item).length > 1) {
      item.iUpdateStatus = 2
    }
  })
  const delete_items = []
  delete_ids.forEach(item => {
    const parm = {
      iUpdateStatus: 4
    }
    parm[primaryKey] = item
    delete_items.push(parm)
  })
  const result = [...edit_item, ...delete_items, ...newItems_]
  return result
}
function comparisonJson(newData_, oldData_, primaryKey, reservedArray = []) {
  const newData = _.cloneDeep(newData_)
  const oldData = _.cloneDeep(oldData_)
  const emptyValue = [undefined, 'undefined']
  const iUpdateStatus = newData.iUpdateStatus
  if (iUpdateStatus === 1) { // 新增
    for (const key in newData) {
      const value = newData[key]
      if (emptyValue.includes(value)) {
        delete newData[key]
      }
    }
  } else { // 修改
    for (const key in newData) {
      if (key === '') {
        debugger
        delete newData[key]
      }
      if (newData[key] === oldData[key] && key !== primaryKey) {
        delete newData[key]
      }
      newData.iUpdateStatus = 2
    }
  }
  delete newData._columns
  return newData
}
// 递归替换action 函数
function recursiveReplaceAction(obj, activeManager) {
  for (const k in obj) {
    const value = obj[k]
    const type_k = typeof value
    if (type_k === 'string') {
      this.replaceItemAction(obj, activeManager)
    } else if (type_k === 'object') {
      this.recursiveReplaceAction(value, activeManager)
    }
  }
}
function replaceItemAction(item, activeManager) {
  const actionProps = ['isHide', 'click', 'clicked', 'disabled', 'changed', 'cleared']
  actionProps.forEach(k => {
    const type = typeof item[k]
    if (type === 'string' && !item[k].startsWith('$')) {
      const funName = '$' + item[k]
      if (!activeManager[funName]) {
        alert(`action---${funName},不存在 `)
        console.error(`action---${funName},不存在 `)
        item[k] = () => {
          console.log(`action---${funName},不存在 `)
        }
      } else {
        item[k] = activeManager[funName]
      }
    }
  })
}
export default {
  parseUrlQueryString,
  parseGlobalParams,
  parseUrlQueryBIDyncAppcodePageName,
  parseMenuGlobalParams,
  recursiveDyncParam,
  filterSingleRow,
  comparisonJson,
  comparisonArray,
  _,
  cloneDeep: _.cloneDeep, // 深拷贝
  recursiveReplaceAction,
  replaceItemAction
}