const tools = {}

/**
 * @param arr [a,b,c]
 *
 * val value
 */
function returnNewObj(data, arr, val) {
  if (arr.length > 1) {
    let k = arr.shift()
    if (!data[k]) {
      data[k] = {}
    }
    returnNewObj(data[k], arr, val)
  } else {
    let curk = arr[0]
    data[curk] = val;
  }
}

/**
 * @param key a
 * @param val {b:{c:''}}|''|1
 * @return a.b.c
 */
function rKeyStrVal(key, val) {
  let nk = key, arr = []
  if (val instanceof Object && !(val instanceof Array)) {
    // for(let k in )
    return nk + '.' + rKeyStrVal()
  }
  return nk
}

/**
 * @param data Object
 * @returns 将对象中 key 为a.b.c 转换为a:{b:{c:''}}
 */
tools.formatData = (data) => {
  let newData = JSON.parse(JSON.stringify(data))
  for (let key in newData) {
    if (key.indexOf('.') > -1) {
      let arr = key.split('.')
      returnNewObj(newData, arr, newData[key])
      delete newData[key]
    }
  }
  return newData
}



/**
 * @param data {a:{b:{c:{}}}}
 *
 * @returns a.b.c
 *
 */
tools.desFormatData = (data) => {
  let newData = {}
  for (let key in data) {
    if (data[key] instanceof Object && !(data[key] instanceof Array)) {
      for (let childK in data[key]) {
        let nk = `${key}.${childK}`
        newData[nk] = data[key][childK]
      }
    } else {
      newData[key] = data[key]
    }
  }
  return newData
}

export default tools
